DBMS - CH-9 - SQL Notes
DBMS - CH-9 - SQL Notes
DBMS - CH-9 - SQL Notes
Step 2: Then we have to click on the download button on the right side.
Step 3: Then on the next page you will find the Start Download button. There
you have to click.
Step 4: Then in the downloaded zip file there will be a setup.exe file. We
have to click & run it.
Step 5: Then the installation will start.
Step 10: After installation, you will find oraclexe folder in the C drive.
Step 11: You have to enter that folder. Then bin folder there you will find
sqlplus exe file. So, your installation is successfully completed.
SQL Concepts
ORACLE TOOLS
The Oracle product is primarily divided into
Oracle Server tools: Oracle Server Product is either called Oracle Workgroup Server or Oracle
Enterprise Server. Oracle Workgroup Server or Oracle Enterprise Server is used for data storage.
Oracle Client tools: The client roll most commonly used for Commercial Application Development is
called Oracle Developer 2000. Oracle Developer 2000, Oracle’s tool box which consists of Oracle Forms,
Oracle Reports and Oracle Graphics. This suite of tools is used to capture, validate and display data
according to user and system needs.
SQL*Plus is a separate Oracle client-side tool. Oracle Workgroup or Enterprise Server is bundled with
this SQL*Plus. It is a product that works on Microsoft Windows 95 and Windows NT both of which are
standard Client based GUI operating systems.
Oracle Workgroup Server and Oracle Developer 2000 are separate products and they must be
purchased separately.
SQL*PLUS
SQL*PLUS is powerful ORACLE support that can take your instructions for oracle. This flexible tool
allows both developers and end-user to issue SQL commands directly against the database.
Database developers use SQL*PLUS to create, fill and monitor an application’s database. End-users of
the database use it to perform ad hoc queries against the database.
ORACLE DATATYPES
When you create table in SQL*PLUS, you must specify the type of data that may appear in each column.
Basic types of oracle are listed below:
Number NUMBER(size) Fixed point number with precision size and scale 0.
Date DATE This data type is used to store date and time information.
Default format is DD-MON-YY.
To enter the dates other than standard format, use the
appropriate functions.
Long LONG Variable length character strings containing up to 2
gigabytes.
Table cannot have more than one Long type of data field.
It cannot be indexed.
It cannot be used with SQL functions, sub queries,
expressions.
It cannot appear in WHERE, GROUP BY, ORGER BY
clauses.
Raw / RAW(size) Raw and Long Raw data types are used to store binary
data such as digitized picture or image.
Long Raw LONG RAW(size)
Raw data type can have a Maximum length of 255 bytes.
Long Raw data type can contain up to 2 GB.
Value stored in columns having LONG RAW data type
cannot be indexed.
DATABASE LANGUAGE
DDL: DDL (Data Definition Language) statements are used to define the database structure or schema.
Some examples:
CREATE - to create objects in the database
ALTER - alters the structure of the database
DROP - delete objects from the database
TRUNCATE - remove all records from a table, including all spaces allocated for the records are
removed
COMMENT - add comments to the data dictionary
RENAME - rename an object
DML: DML (Data Manipulation Language) statements are used for managing data within schema objects.
Some examples:
SELECT - retrieve data from the a database
INSERT - insert data into a table
UPDATE - updates existing data within a table
DELETE - deletes all records from a table, the space for the records remain
(<ColumnName1><DataType>(<size>),
<ColumnName2><DataType>(<size>), …… );
(2) Inserting Data into Tables using INSERT INTO command: Once a table is created, most natural
thing to do is load this table with data to be manipulated later.
When inserting a single raw of data into the table, insert operation:
Character value (expression) placed within the INSERT INTO statement must be enclosed in single
quotes (‘).
(3) Viewing data in the Tables: Once data has been inserted into a table, the next most logical
operation would be to view what has been inserted. The SELECT SQL verb is used to achieve this.
The SELECT command is used to retrieve rows selected from one or more tables.
The SELECT statement can be used to Display some or all the columns from a specified table.
Display some or all of the rows from a specified table.
Display calculated values from the table.
Display statistical information from the tables, like averages or sums of column values.
Combine information from two or more tables.
All Rows and All Columns: When data from all rows and columns from the table are to be viewed the
syntax of the SELECT statement will be used. The syntax is:
Oracle allows the use of the Meta character asterisk (*), this is expanded by Oracle to mean all rows
and all columns in the table.
FROM <TableName>;
Note:
The SELECT clause followed by the FROM clause are required for any SQL query.
Not all columns need to be selected.
Columns are displayed left or right in the order specified.
SELECT list items must be separated by commas.
Rows are returned in an arbitrary manner.
Users may query only tables they have created or tables to which they have granted
access.
If you want to see which tables you have in your account, a special query can be made.
Query is: SELECT* FROM tab;
If you want conditional retrieval of rows i.e. only those rows which satisfy certain condition.
You can use WHERE clause in the SELECT statement.
Note:
Columns specified n the WHERE clause must be part of the table specified in the form clause.
Columns used in the WHERE clause do not have to be in SELECT list.
The WHERE clause must specify character data in the same case (upper or lower) that it is in
the database.
The comparison operators that can be used in SQL statements are < ,> , <= .., >= , = , <>.
Elimination of duplicates from the select statement:
A table could hold duplicate rows. In such a case, to see only unique rows, you have to use DISTINCT
clause.
The DISTINCT clause allows removing duplicates from the result set. The DISTINCT clause can be only
be used with SELECT statements.
FROM <TableName>;
The SELECT DISTINCT * SQL syntax scans through entire rows, and eliminates rows that have
exactly the same contents in each column.
Oracle allows data from a table to be viewed in a sorted order. The rows retrieved from the table will
be sorted in either ascending or descending order depending on the condition specified in the SELECT
sentence.
Sort Order can be ascending (use word asc) or descending (use word desc). In case there is no
mention of the sort order, the Oracle engine sorts in ascending order by default.
Example: Create a table named ACCT_DTLS having three fields i.e. ACCT_NO, BRANCH_NO
and CURBAL from the table ACCT_MSTR and rename field CURBAL to BALACE.
The Source table is a table identified in the SELECT section of this SQL sentence. The Target
table is one identified in the CREATE section of this SQL sentence. This table sentence populates
the Target table with data from the Source table.
To create a Target table without the records from the source table (i.e. create the structure
only), the select statement must be a have a WHERE clause. The WHERE clause must specify
the condition that cannot be satisfied.
Example: Create a table named ACCT_DTLS having three fields i.e. ACCT_NO, BRANCH_NO
and CURBAL from the table ACCT_MSTR and rename field CURBAL to BALACE. The
table ACCT_DTLS should not be populated with any records.
WHERE 1=2;
(5) Inserting Data into a Table from another Table: To insert data one row at a time into a table, it is
quite possible to populate a table with data that already exists in another table.
Here the WHERE clause is optional. If you are not specify the WHERE clause then all the from source
table to target table is copied.
Example: Insert only the savings bank accounts details in the target table ACCT_DTLS from
the source table ACCT_MSTR.
(6) Delete Operations:The DELETE command deletes rows from the table that satisfies the condition
provided by its WHERE clause, and returns the number of records deleted.
(7) Updating the contents of a table: The UPDATE command is used to change or modify data values
in table.
Example: Update the address details by changing its city name to Ahmedabad.
Example: Update the branch details by changing the Vile Parle (HO) to Head Office.
(8) Modifying the Structure of Tables: The structure of a table can be modified by using ALTER TABLE
command. ALTER TABLE allows changing the structure of an existing table. With ALTER TABLE it is
possible to add or delete columns, change the data type of existing columns.
Adding New Columns:
Syntax: ALTER TABLE <TableName>
ADD (<NewColumnName><DataType>(<Size>),
<NewColumnName><DataType>(<Size>), …);
MODIFY(<ColumnName><NewDataType>(<NewSize>));
Example: Alter table BRANCH_MSTR to allow the NAME field to hold maximum of 30
characters.
The following tasks cannot be performed when using the ALTER TABLE clause:
(10) Truncating Tables: TRUNCATE TABLE empties a table completely. Logically, this is equivalent to a
DELETE statement that deletes all rows, but there are practical differences under some
circumstances.
TRUNCATE TABLE differs from DELETE in the following ways:
1. Truncate operations drop and re-create table, which is much faster than deleting rows one by
one.
2. Truncate operations are not transaction-safe (i.e. an error will occur if an active transaction or
an active table lock exists).
3. The numbers of deleted rows are not returned.
(11) Destroying Tables: Sometimes tables within a particular database become obsolete and need to
be discarded. In such situation using DROP TABLE statement with the table name can destroy a
specific table. If a table is dropped all records held within it are lost and cannot be recovered.
Syntax: DROP TABLE <TableName>;
Example: Remove the table BRANCH_MSTR along with the data held.
(12) Constraints:
NOT NULL: NOT NULL column constraint ensures that a table column can not be left empty, It
Implies that a value must be entered into the column.
UNIQUE Constraint defined at the column level: UNIQUE column constraint permits multiple
entries of null into the column.
PRIMARY KEY Constraint defined at the column level: PRIMARY KEY uniquely identifies a row.It
will not allow duplicate values, also not allow null values.
PRIMARY KEY Constraint defined at the table level: when we are using composite PRIMARY KEY
.
Syntax: PRIMARY KEY (<ColumnName>,<ColumnName>);
FOREIGN KEY Constraint: A FOREIGN KEYa column or group of columns whose values are derived
from the primary key or unique key from other table
A table in which foreign key is defined is called child table or detailed table.
A table that defines primary key and reference by the foreign key called master table or parent
table.
Example: Create Table Student (Sid Number(5), BookId Number(5) references Book(BookId)) ;
FOREIGN KEY Constraint with on delete cascade: Because of the cascade delete when a record
in parent table is deleted, records in the child table will also deleted.
Example: Create Table Student (Sid Number(5), BookId Number(5), FOREIGN KEY(BookId)
references Book(BookId) ON DELETE CASCADE) ;
FOREIGN KEY Constraint with on delete set NULL: If a record in the parent table is deleted than
the corresponding records in the child table will set to null, the records in the child table will not
be deleted.
Example: Create Table Student (Sid Number(5), BookId Number(5), FOREIGN KEY(BookId)
references Book(BookId) ON DELETE SET NULL) ;
Example: Create Table Licence (LId Number(5), age Number(5) CHECK (age >= 18)) ;
Example: Create Table Licence (LId Number(5), age Number(5), CHECK (age >= 18)) ;
The following SQL statement selects all students with a Name starting with "a":
(14) SQL IN Operator :IN operator allows to specify multiple values using WHERE clause.
The following SQL statement selects all students that are located in "Germany", "France" or "UK":
Example: SELECT * FROM Students
WHERE Country IN ('Germany', 'France', 'UK');
(15) SQL BETWEEN Operator: Whenever we want to select value within range we can use
BETWEENoperator.
(16) JOIN
Here are the different types of the JOINs in SQL:
(INNER) JOIN: Returns records that have matching values in both tables
LEFT (OUTER) JOIN: Returns all records from the left table, and the matched records from the
right table
RIGHT (OUTER) JOIN: Returns all records from the right table, and the matched records from
the left table
FULL (OUTER) JOIN: Returns all records when there is a match in either left or right table
INNER JOIN SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
INNER JOIN table2
ON table1.matching_column = table2.matching_column;
Example:
Student(StudentID, CouseID)
Courses(CouseID, CourseName)
AVG() Syntax
SELECT AVG(column_name)
FROM table_name
WHERE condition;
COUNT() Syntax
SELECT COUNT(column_name)
FROM table_name
WHERE condition;
SUM() Syntax
SELECT SUM(column_name)
FROM table_name
WHERE condition;
MIN() Syntax
SELECT MIN(column_name)
FROM table_name
WHERE condition;
MAX() Syntax
SELECT MAX(column_name)
FROM table_name
WHERE condition;
GROUP BY: The GROUP BY statement groups rows that have the same values into summary rows,
like "find the number of students in each city".
The GROUP BY statement is often used with aggregate functions
(COUNT(), MAX(), MIN(), SUM(), AVG()) to group the result-set by one or more columns.
HAVING :The HAVING statement groups rows that have the same values into summary rows with
consition like "find the number of students in each city where count>5".
SUBQUERIES: A subquery is a query within a query. This means a subquery is a SELECT statement
that is nested within another SELECT statement and which returns intermediate results. It is also
termed as nested query. The statement containing a subquery is called a parent statement. The
parent statement uses the rows (i.e. result set) returned by the subquery.
Using EXISTS: The EXISTS operator is used to test for the existence of any record in a
subquery.
Using ANY/ALL: The ANY and ALL operators allow you to perform a comparison between a
single column value and a range of other values.
Example 1: List out employee name whose dname is abc and xyz using subquery.
Answer:select ename from emp where deptnoin(select deptno from dept where dname = 'abc' or
dname = 'xyz');
Explanation: First Subquery is executed and values are replaced in query.
DEPTNO
------
10
20
Then the parent query is executed like.
selectename from emp where deptno in(10,20);
Example: List out employee name whose dname is not abc and xyz using subquery.
Answer:select ename from emp where deptno not in(select deptno from dept where dname = 'abc'
or dname = 'xyz');
Explanation: First Subquery is executed and values are replaced in query.
DEPTNO
------
10
20
Then the parent query is executed like.
selectename from emp where deptno not in(10,20);
INDEXES
Indexes that allow duplicate values for the indexed columns i.e. Duplicate Index.
Indexes that deny duplicate values for the indexed columns i.e. Unique Index.
Creation of an Index:
An index can be created on one or more columns. Based on the number of columns included in the index,
an index can be:
Simple Index
Composite Index
An index is created on a single column of a table is called a Simple Index. The syntax for creating simple index
that allows duplicate values is as described:
An index is created on more than one column of a table is called a Composite Index. The syntax for creating
composite index that allows duplicate values is as described:
A unique index can also be created on one or more columns. If an index is created on a single column, it is
called Simple Unique Index. The syntax for creating simple unique index is as follows:
If an index is created on more than one column, it is called Composite Unique Index. The syntax for creating
composite unique index is as follows:
Indexes associated with the tables can be removed by using the DROP INDEX command.
Syntax:DROP INDEX<IndexName>;
Example: DROP INDEX idx_c_no;
When a table, which has associated indexes, is dropped, the oracle engine automatically drops all the
associated indexes as well.
VIEW
Comparison Operators:
Comparison operators compare one expression with another. The result of such a comparison can be
TRUE, FALSE, or UNKNOWN. Table given below lists comparison operators.
Operator Purpose Example
Logical Operators:
A logical operator combines the results of two component conditions to produce a single result based on
them or to invert the result of a single condition. Table given below lists logical operators.
SQL FUNCTIONS:
The Oracle Table DUAL :
The DUAL is a table own by system, The structure of DUAL table is viewed as follows.
DESC DUAL;
CHARACTER FUNCTIONS:
REPLACE('www.yahoo.com
REPLACE(s, Returns s with all occurrences of ', 'yahoo', 'google')
s1[, s2]) substring s1 replaced with s2. By = 'www.google.com'
default s2 is NULL and all
occurrences of s1 are removed.
ABS(-25.52) = 25.52
ABS(d) Returns the absolute value of the double d. Select ABS(-25.52)
“Absolute” from DUAL;
FLOOR(24.8) = 24,
FLOOR(d) Returns the largest integer less or equal to d.
FLOOR(-24.8)= -25
POWER(d,
Returns d to the pth power (dp). POWER(2,5)= 32
p)
ROUND(2.6586,2) =
Returns d rounded to i digits of precision to the 2.66
ROUND(d,
right of the decimal point. If i is negative, d is
i) ROUND(289.6586,-2)=
rounded to the left of the decimal point.
300
TRUNC(256.8888,2) =
Returns d truncated to i digits of precision to 256.88
TRUNC(d,
the right of the decimal point. If i is negative, d
i) TRUNC(256.8888,-2) =
is truncated to the left of the decimal point.
200
DATE FUNCTIONS:
Implicit Date-to-String conversion is based on the value of the NLS_DATE_FORMAT variable. To change
its value use the ALTER SESSION command:
ALTER SESSION SET NLS_DATE_FORMAT = 'DD-MM-YYYY HH24:MI:SS';
MONTHS_BETWEEN('01-JAN-
Returns the number of months that
2009',SYSDATE) = 4
dt1 is later than dt2. A whole
MONTHS_BETWEEN
number is returned if dt1 and dt2 are
(dt1, dt2)
the same day of the month or if both
MONTHS_BETWEEN('01-JAN-
are th last day of the month.
2007',SYSDATE) = -19
CONVERSION FUNCTIONS
Function Description
TO_NUMBER(s[, fmt[, Returns the numeric value represented by the string s. The
nls]]) format string fmt specifies the format the that s appears in.
(1) TO_CHAR FUNCTION: In Oracle/PLSQL, the TO_CHAR function converts a number or date to a string.
Examples – Numbers:
2. to_char(1210.73,
would return '1,210.73'
'9,999.99')
3. to_char(1210.73,
would return '$1,210.73'
'$9,999.00')
Examples – Dates:
6.
to_char(sysdate, 'FMMonddth, YYYY') would return 'Jul 9th, 2008'
You will notice that in some examples, the format_mask parameter begins with "FM". This
means that zeros and blanks are suppressed. This can be seen in the examples below.
The zeros have been suppressed so that the day component shows as "9" as opposed to "09".
(2) TO_DATE FUNCTION: In Oracle/PLSQL, the TO_DATE function converts a string to a date.
The following is a list of options for the format_mask parameter. These parameters can be used
in many combinations.
For example:
1. to_date('2008/07/09',
would return a date value 09-07-2008 00:00:00
'yyyy/mm/dd')
3. to_date('2008Mar15',
would return a date value 15-03-2008 00:00:00
'yyyymmdd')
(3) TO_NUMBER FUNCTION: In Oracle/PLSQL, the TO_NUMBER function converts a string to a number.
For example:
1. to_number('1210.73',
would return the number 1210.73
'9999.99')
Since the format_mask and nls_language parameters are optional, you can simply convert a text
string to a numeric value as follows:
to_number('1210.73') would return the number 1210.73
Objects that are created by a user are owned and controlled by that user.
If a user wishes to access any of the objects belonging to another user, the owner of the object
will have to give the permission for each access. This is called Granting of Privileges.
Privileges once given can be taken back by the owner of the object. This is called Revoking of
Privileges.
Granting Privileges Using the GRANT statement:The Grant statement provides various types of
access to database objects such as tables, views and sequences and so on.
ON<Object Name>
TO<User Name>
OBJECT PRIVILEGES:
Each object privileges that are granted authorize the grantee to perform some operation on the object.
The user can grant the privileges or grant only specific object privileges.
DELETE Allows the grantee to remove the record from a table with the DELETE
Command.
INDEX Allows the grantee to create an index on the table with the INDEX Command.
INSERT Allows the grantee to add records to the table with the INSERT Command.
SELECT Allows the grantee to query the table with the SELECT Command.
UPDATE Allows the grantee to modify the records in the table with the UPDATE
Command.
The WITH GRANT OPTION allows the grantee to in turn grant object privileges to other users.
Examples: a. Give the user Bandish all data manipulation permission on the table
product_master.
GRANT ALL ON product_masterTO Bandish;
b. Give the user Sagar only the permission to view and modify records in the
table client_master.
GRANT select, update ON client_masterTO Sagar;
c. Give the user Alap all data manipulation privileges on the table ACCT_MSTR
along with an option to further grant permission on the ACCT_MSTR table to
other users.
GRANT ALL ON ACCT_MSTR TOAlapWITH GRANT OPTION;
d. Give the user Jashvant to view records from the TRANS_MSTR table. The
table originally belongs to the user Ankit, who has granted you the privilege
to pass on the privileges that you have to others using GRANT privilege
option.
GRANT SELECT ON Ankit.TRANS_MSTR TO Jashvant;
Referencing a Table Belonging To Another User: Once a user has privileges to access another user’s
object(s), the user can access the table by prefixing the table with the name of the owner.
Example: View the contents of the FD_MSTR table that belongs to Alap.
Privileges once given can be denied to a user using the REVOKE command.
ON<Object Name>
FROM<User Name>;
Examples: b. All privileges on the table NOMIEE_MSTR have been granted to Rahul. Take
back the Delete privilege on the table.
REVOKE DELETE ON NOMIEE_MSTR FROM Rahul;
d. Darshan has the permission to view records from FD_MSTR. Take back this
permission. Note that Hardik the original owner of FD_MSTR table.
REVOKE SELECT ON Hardik.FD_MSTR FROM Darshan;