DBMSSQL Plus Mat
DBMSSQL Plus Mat
DBMS/SQL+
Training Workshop
Student Guide
Copyright © 2005 Patni Computer Systems Ltd., Akruti, MIDC Cross Road No. 21,
Andheri (E), Mumbai 400 093. All rights reserved. No part of this publication
can be reproduced in any way, including but not limited to photocopy,
photographic, magnetic, or other record, without the prior agreement and
written permission of Patni Computer Systems.
Index
1. INTRODUCTION TO DATABASE .........................................................................3
1.1. Introduction.........................................................................................................3
1.2. Characteristics of DBMS ....................................................................................4
1.3. The DBMS Models or Architectures..................................................................6
1.4. Relational DBMS ..................................................................................................7
2. INTRODUCTION TO SQL .....................................................................................12
2.1. What is SQL ?.....................................................................................................12
2.2. Creation of Database Objects ........................................................................14
2.3. Modification of Existing Database Objects ..................................................17
2.4. Deletion Of Database Objects........................................................................19
2.5. Addition Of Data into Tables..........................................................................20
2.6. Modification of Existing Data in Tables........................................................22
2.7. Deletion of Data from Tables.........................................................................22
2.8. Transaction Control .........................................................................................23
2.9. How to Retrieve Data from Tables ? .............................................................25
2.10. SQL Functions................................................................................................39
3. JOINS AND SUBQUERIES ...................................................................................48
3.1. Joins....................................................................................................................48
3.2. Subqueries .........................................................................................................53
4. ADVANCED SQL.....................................................................................................58
4.1. Index ...................................................................................................................58
4.2. Synonym .............................................................................................................58
4.3. Sequence............................................................................................................59
4.4. View....................................................................................................................59
5. PL/SQL ......................................................................................................................61
5.1. Introduction to PL/SQL ...................................................................................61
5.2. PL/SQL block and its Sections........................................................................61
5.3. Declaration Section..........................................................................................62
5.4. Variable Scope And Visibility .........................................................................65
5.5. Programming Constructs ................................................................................69
6. ERROR HANDLING ...............................................................................................74
6.1. Types of Errors in PL/SQL...............................................................................74
6.2. Declaring Exceptions .......................................................................................74
7. STORED PROCEDURES AND FUNCTIONS .....................................................78
7.1. Procedure ..........................................................................................................78
7.2. Functions ...........................................................................................................82
7.3. Packages ............................................................................................................84
Page 1 of 92
DBMS/SQL+
Page 2 of 91
DBMS/SQL+
1. Introduction to Database
1.1. Introduction
DBMS
END USER TOOLS
APPLICATIONS
DATA
END END
USER USER
Page 3 of 92
DBMS/SQL+
In today’s environment, there must be one key individual who is responsible for
the overall centralized control of the organization’s data. We refer to the
person as the data base administrator (DBA). It concerns policy-oriented tasks
regarding data strategy and overall data planning. The DBA is responsible for
the actual entities in the business environment that will be represented in the
database. The DBA also works with end users and system analysts to document
the data that will be stored in the database. The DBA initially studies the
System and accordingly decides the types of data to be used, then the
structures to be used to hold the data and the interrelationships between the
data structures. He then defines data to the DBMS. The DBA also ensures the
security of the database. The DBA usually controls access to the data through
the user codes and passwords and by restricting the views or operations that the
users can perform on the database.
Page 4 of 91
DBMS/SQL+
Page 5 of 91
DBMS/SQL+
1.2.8. Security
DBMSs provide tools by which the DBA can ensure security of the database.
Page 6 of 91
DBMS/SQL+
Page 7 of 91
DBMS/SQL+
DEPT table
Deptno Dname Loc
10 Accounting New York
20 Research Dallas
30 Sales Chicago 'row' or 'tuple'
40 Operations Boston
á
'column' or 'attribute'
EMPLOYEE table
Empno Empname Job Mgr Deptno
7369 Smith Clerk 7902 20
7499 Allen Salesman 7839 30
7566 Jones Manager 7839 20
7839 King President 10
7902 Ford Analyst 7566 20
Page 8 of 91
DBMS/SQL+
Uniqueness: At any give time, no two rows of T have the same value for CK
Page 9 of 91
DBMS/SQL+
Note that the relational model requires every table to have at least one
candidate key, and hence requires every table to have a primary key. This
requirement is equivalent to the requirement that, at any given time, no
two rows in the table are identical.
The referential integrity rule specifies that if a foreign key in table A refers
to the primary key in table B, then every value of the foreign key in table A
must be null or must be available in table B.
This means that no primary key value can be deleted if there are some
foreign key values dependent on it. i.e Dept no 10 cannot be deleted
because there are some employees assigned to deptno 10.
Page 10 of 91
DBMS/SQL+
Page 11 of 91
DBMS/SQL+
2. Introduction to SQL
2.1. What is SQL ?
SQL or Structured Query Language is the set of commands, which is used
for interacting with Relational Databases. ANSI has standardized the
commands and all relational databases conform to this standard. Most RDBMS
provide extensions to it to make the life of the application programmer
easier.
SQL commands are the instructions given for some operation on the database
and the fact that SQL DML like SELECT, UPDATE and DELETE statements
typically operate on entire sets of rows, instead of just one row at a time.
Hence, SQL is called set-level language.
Page 12 of 91
DBMS/SQL+
1. Non-Procedural Language:
• Set-level languages such as SQL are sometimes described as
“nonprocedural,” on the grounds that the users specify what, not how
(i.e., they say what data they want without specifying a procedure for
getting it). Perhaps a better way of putting matters is to say that
languages like SQL are at a higher level of abstraction than languages
like COBOL or C.
• It processes sets of records rather than just one record at a time.
• It provides automatic navigation to the data. The process of “navigating”
around the physical database to locate the desired data is performed
automatically by the system, not manually by the user
2. Language For All Users:
• System Administrators
• Database Administrators
• Security Administrators
• Application Programmers
• End-Users
Datatype Description
Page 13 of 91
DBMS/SQL+
Syntax
Page 14 of 91
DBMS/SQL+
Any object created by a user is accessible to the user and the DBA only. To
make the object accessible to other users, the creator or the DBA must
explicitly give permission to others. SEE Section 3.12 for granting permissions.
Example:
CREATE TABLE emp
(
empno NUMBER(4),
ename VARCHAR2(10) ,
deptno NUMBER(2) ,
job CHAR(9) ,
hiredate DATE );
Page 15 of 91
DBMS/SQL+
In EMP table, for deptno column, if we want to allow only those values that
already exist in deptno column of DEPT table, we must enforce what is known
as REFERENTIAL INTEGRITY.
Page 16 of 91
DBMS/SQL+
In above example FOREIGN KEY has been declared as a table constraint. Same
can be given as a column constraint as follows.
A new table will be created. It will contain empno, ename, hiredate of all
employees hired after 1st Jan 1982. Constraints on an old table will not be
applicable for a new table
Page 17 of 91
DBMS/SQL+
Page 18 of 91
DBMS/SQL+
Once all the required columns have been marked as unused, we can use the
following command to remove the columns permanently. Columns once
marked as unused cannot be recovered. Marking the columns as unused does
not release the space occupied by them back to the database. Also until you
drop these columns actually, they continue to count towards the absolute
limit of 1000 columns per table. Also, if you mark a column of data type
LONG as UNUSED, you cannot add another LONG column to the table until
you actually drop the unused LONG column.
Before the user issues DROP COLUMN command, the user must have
exclusive control over the table.
Page 19 of 91
DBMS/SQL+
For example
DROP TABLE EMP;
A table that is dropped cannot be recovered. When a table is dropped,
dependent objects such as indexes are automatically dropped. Synonyms and
views created on the table remain, but give an error if they are referenced. You
cannot delete a table that is being referenced by another table. To do so use
the following
DROP TABLE table-name CASCADE CONSTRAINTS;
DROP TABLE dept CASCADE CONSTRAINTS;
If new_emp is a synonym for a table, then the table is not affected in any way.
Only the duplicate name is removed.
• If values are specified for all columns in the order specified at creation,
then col_names can be omitted
• Values should match datatype of the respective columns
• Number of values should match the number of column names mentioned
• All columns declared as NOT NULL should be supplied with a value
• Character strings should be enclosed in quotes
• DATE values should be enclosed in quotes
• VALUES will insert one row at a time
• Query will insert all the rows returned by the query
• Table_name can be a table or a view or a synonym name
• If table_name is a view, then following restrictions apply
• View CANNOT have a GROUP BY, CONNECT BY, START WITH, DISTINCT,
UNION, INTERSECT OR MINUS clause or a join
• If view has WITH CHECK OPTION clause, then a row that cannot be returned
by the view will not be inserted
Page 20 of 91
DBMS/SQL+
• This row will be created if all the constraints like NOT NULL are satisfied.
Inserting rows in a table from another table.
When the above INSERT statement is executed from the SQL prompt, the user is
prompted with following
Deptno, dname and loc variables values will be obtained at runtime and
substituted in the SQL statement before execution of the statement. The
Page 21 of 91
DBMS/SQL+
ampersand & before the variable name indicates that, what follows is a
variable and not a value.
Since there will be direct substitution, quotes are not required when you give
input to dname and loc as quotes are already present. If the statement was
given as
Provides automatic navigation to the data. If WHERE is omitted, all the rows
will be updated and if WHERE is specified only those rows that satisfy the
condition will be updated.
UPDATE emp
SET ename = 'ADAM'
WHERE ename = 'ADAMS';
For making salary of SMITH equal to that of employee no 7369.
UPDATE emp
SET SAL = (SELECT SAL FROM emp
WHERE empno = 7369)
WHERE ename = 'SMITH';
All employees other than the PRESIDENT will have the same job, salary and
commission as that of ALLEN.
UPDATE emp
SET (job,sal,comm) = (SELECT job,sal,comm FROM emp
WHERE ename = 'ALLEN')
WHERE NOT job = 'PRESIDENT';
If WHERE is omitted, all rows from the table are removed and if WHERE is
specified all rows, which satisfy the condition, are removed.
Page 22 of 91
DBMS/SQL+
DELETE emp
WHERE ename = 'JOHN';
Page 23 of 91
DBMS/SQL+
2.8.1. COMMIT
Syntax: COMMIT;
Example:
SAVEPOINT spt1;
UPDATE emp
SET sal=sal+1000
WHERE deptno=10;
ROLLBACK to spt1;
The SAVEPOINT command divides a transaction into smaller sub units or logical
units. Very large, complex transactions might require dozens or hundreds of DML
commands, it may help your application design if you can hold at certain points
and ROLLBACK or COMMIT just one part of the total transaction, an example of
this is a complex user information input such as entering mathematical
modeling data. The SAVEPOINT command has a parameter, which is the name of
the savepoint. This name can be used to rollback all updates from the time
Page 24 of 91
DBMS/SQL+
when you issued the named savepoint. You can reuse the savepoint name, each
time you redeclare an existing savepoint the old savepoint of that name is
deleted.
Changes made to the database without COMMIT may be abandoned using the
ROLLBACK statement. When a transaction is rolledback, it is as if the
transaction never occurred. When a transaction is rolled back, the following
events take place
SAVEPOINT delete_finished
ROLLBACK TO delete_finished
ROLLBACK
Page 25 of 91
DBMS/SQL+
• It is NOT necessary to retrieve all the COLUMNS of the table. If LOC is not
required, then the following query can be used
• It is NOT necessary to list the column names in the same order as done at
the time of table creation. If dept name is to be displayed followed by dept
number, then use
• If all columns are to be retrieved, then instead of listing the column names,
use. The star or asterisk is shorthand for a list of all column names in the
table(s) named in the FROM clause, in the left-to-right order in which those
columns appear in the relevant tables(s)
• When rows are retrieved and displayed, the column heading is same as the
column name. To change the heading from LOC to LOCATION, use
DEPTNO
------------
20
30
30
20
30
30
10
20
10
…
14 rows selected
DISTINCT Parameter
In the above output, some of the values have been repeated. By default, all
values are retrieved. If you wish to remove duplicate values, then say
Note: It just so happens in this particular example that each row contains a
single value; the effect of the DISTINCT specification is therefore to eliminate
duplicate values. In general, however, DISTINCT means “eliminate duplicate
rows.
COMPARISON Predicate
The comparison predicates specifies comparison of two values. It is of the form
< Expression> < operator > < Expression>
< Expression> <operator> <subquery> --- Will be discussed Later
The operators used are
Page 27 of 91
DBMS/SQL+
= Equal to
<> not equal to
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal
to
The BETWEEN condition is really just shorthand for a condition involving two
individual comparisons “ANDed” together.
Page 28 of 91
DBMS/SQL+
• To list names and sal of all employees whose sal is between 2000 and 3000
including 2000 and 3000
SELECT ename,sal FROM emp WHERE sal BETWEEN 2000 AND 3000;
ENAME SAL
---------- ----------
CLARK 2450
BLAKE 2850
JONES 2975
SCOTT 3000
FORD 3000
ENAME HIREDATE
----------- ----------------
SCOTT 09-DEC-82
MILLER 23-JAN-82
Page 29 of 91
DBMS/SQL+
To search for characters % and _ in the string itself we have to use an escape
character. For example to search for string NOT_APP in column status we have
to use the form
Status like 'NOT\_APP' ESCAPE \' ' The use of \ as escape character is purely
arbitrary.
• To list employees whose name begins with 'J' and has 'N' as the 3rd
CHARacter, say
SELECT ename FROM emp WHERE ename LIKE 'J_N%';
ENAME
----------
JONES
Page 30 of 91
DBMS/SQL+
Even though TURNER has not received any comm, the row has been retrieved
because it contains a 0 and not a NULL. NULL is a special representation without
any value.
• To list the BIG BOSS of the company, except for BIG BOSS, all employees
have a value in the MGR column.
Page 31 of 91
DBMS/SQL+
• To list employees hired after 01/09/81 and working in dept NUMBER 10, use
Aggregate Functions
Although quite powerful in many ways, the SELECT statement as so far
described is still inadequate for many practical problems. For example, even a
query as simple as “How many employees are there?’ cannot be expressed using
the constructs introduced up till now. SQL therefore provides a number of
special aggregate (or column) functions to enhance its basic retrieval power.
Some of the aggregate functions available are COUNT, SUM, AVG, MAX and MIN.
Apart from the special case of “COUNT(*)”, each of these functions operates on
the collection of scalar values in one column of some table.
SQL provides a set of built-in functions for producing a single value for an entire
group. These functions are called Set functions or Aggregate functions.
These functions can work on a normal result table or a grouped result table. If
the result is not grouped then the aggregate will be taken for the whole result
table.
Page 32 of 91
DBMS/SQL+
1. COUNT(*)
2. SUM(COL_NAME | EX PRESSION)
SUM(SAL)
---------------
29025
Page 33 of 91
DBMS/SQL+
AVG is similar to SUM. AVG returns the average of the values in the column. The
restrictions, which apply on SUM also, apply on AVG.
To find the average salary of all employees
SELECT AVG(sal) FROM emp;
AVG (SAL)
---------------
2073.21429
MIN returns the smallest value in the column. MIN accepts columns, which are
NON-NUMERIC too.
To find the minimum salary paid to any employee
SELECT MIN(sal) FROM emp;
MIN(SAL)
--------------
800
To list the employee who heads the list alphabetically, use
SELECT MIN(ename) FROM emp;
The GROUP BY operator causes the table represented by the FROM clause to
be rearranged into partitions or groups, such that within one group all rows
have the same value for the GROUP BY column. Note that the table is not
physically arranged in the database.
Page 34 of 91
DBMS/SQL+
All the SELECT statements we have used until now have acted on data as if
the data is in a single group. But the rows of data in some of the tables can
be thought of as being part of different groups.
For example, the EMP table contains employees who are CLERKS, SALESMEN
etc. If we wish to find the minimum salary of each group of employees, then
none of the clauses that we have seen until now are of any use.
The GROUP BY are used to group the result table derived from earlier FROM
and WHERE clause. HAVING is used to apply search condition on these
groups.
When a GROUP BY clause is used, each row of the resulting table will
represent a group having same values in the column(s) used for grouping.
HAVING clause then acts on the resulting grouped table to remove the row
which does not satisfy the criteria in the HAVING search condition.
The GROUP BY clause is of the form
GROUP BY < column list >
The columns specified must be selected in the query. If a table is grouped,
the select list should have columns and expressions, which are single-valued
for a group. These are
Page 35 of 91
DBMS/SQL+
Page 36 of 91
DBMS/SQL+
Page 37 of 91
DBMS/SQL+
The columns to be used for ordering are specified by using the column names or
by specifying the serial number of the column in the select list. The sort is done
on the column in Ascending or Descending order. The default is Ascending.
Note: GROUP BY does not imply ORDER BY.
To list all employees in the ascending order by name
SELECT ename, sal from emp order by ename;
ENAME SAL
---------- ----------
ADAMS 1100
ALLEN 1600
BLAKE 2850
CLARK 2450
FORD 3000
JAMES 950
JONES 2975
KING 5000
MARTIN 1250
MILLER 1300
SCOTT 3000
SMITH 800
TURNER 1500
WARD 1250
To select all employees sorted dept wise in ascending order and within dept
salary wise in descending order for deptno 10 and 20.
Page 38 of 91
DBMS/SQL+
To select all employees along with their annual salary sorted on the basis of the
annual salary.
SELECT ename, sal * 12 "Annual Salary" FROM emp
ORDER BY 2 DESC;
If you call a SQL function with a null argument, the SQL function
automatically returns null.
Page 39 of 91
DBMS/SQL+
1. UPPER(string)
2. LOWER(string)
3. INITCAP(string)
Converts the first character of each word in string to uppercase and the rest of
the characters to lowercase.
SELECT INITCAP(ename),empno FROM emp
WHERE job = 'CLERK';
INITCAP(ENAME) EMPNO
----------------- -----------
Smith 7902
Adams 7788
James 7698
Miller 7782
4. LPAD(string1,n,string2)
Adds string2 before string1 as many times as required to make the string1 length
equal to n chars.
To right align the names of employees
Page 40 of 91
DBMS/SQL+
5. LTRIM(string,CHAR set)
Removes chars from beginning of string as long as the character matches one of
the chars in the CHAR set.
SELECT ename,LTRIM(ename,'MALICE') FROM emp;
ENAME LTRIM(ENAME,
----------- -----------------------
SMITH SMITH
ALLEN N
WARD WARD
JONES JONES
MARTIN RTIN
BLAKE BLAKE
CLARK RK
SCOTT SCOTT
KING KING
TURNER TURNER
ADAMS DAMS
JAMES JAMES
FORD FORD
MILLER R
14 rows selected.
6. RPAD(string1,n,string2)
7. RTRIM(string,CHAR set)
8. SUBSTR(CHAR,m,n)
This function returns the string from the m th character of the string to the n th
character.
Page 41 of 91
DBMS/SQL+
NOTE: The table named DUAL is a small table in the data dictionary that Oracle
and user-written programs can reference to guarantee a known result. This
table has one column called DUMMY and one row containing the value X.
1. SYSDATE
Truncates the time part from the DATE. This is required when we do DATE
calculations.
3. MONTHS_BETWEEN (DATE1,DATE2)
SELECT empno,MONTHS_BETWEEN(TRUNC(sysdate),hiredate)
FROM emp;
EMPNO MONTHS_BETWEEN(TRUNC(SYSDATE),HIREDATE)
--------- -------------------------------------------------------------
7369 10.36
7499 1.562
7521 0.721
. .
14 rows selected
4. ADD_MONTHS(DATE1,int1)
Page 42 of 91
DBMS/SQL+
5. TO_CHAR(DATE1,format)
6. ROUND(n,m)
Page 43 of 91
DBMS/SQL+
Number
--------
17.2
Number
-----------
20
7. LASTDAY(d)
Returns the date of the last day of the month that contains d. You might use
this function to determine how many days are left in the current month.
SELECT SYSDATE,
LAST_DAY(SYSDATE) "Last",
LAST_DAY(SYSDATE) - SYSDATE "Days Left"
FROM DUAL;
8. NEXT_DAY(d, char)
Returns the date of the first weekday named by char that is later than the date
d.
Numeric Functions
9. TRUNC(n,m)
Page 44 of 91
DBMS/SQL+
Number
-----------
10
10. ROUND(N,M)
Round
----------
15.2
11. CEIL(n)
12. FLOOR(n)
There are some more numeric functions available, Please refer to the online
documentation for more help.
Page 45 of 91
DBMS/SQL+
a) LENGTH (string)
7 Length in characters
b) NVL(exprl,n)
ENAME COMMISSION
ALLEN 300
WARD 500
MARTIN 1400
BLAKE 0
TURNER 0
JAMES 0
2.10.3. DECODE:
A Special function used to evaluate expression. This works like the IF-THEN-
ELSE conditional loop.
Decode(col_name,condition1,value1,condition2,value2…..,default value)
Select Ename,job,DECODE(job,’SALESMAN’,’ELIGIBLE’,’PRESIDENT’,’HEAD
PERSON’,’NOT ELIGIBLE’) “COMM ELIGIBLITY” FROM EMP;
Page 46 of 91
DBMS/SQL+
Raised
9
REPLACE: Returns char with every occurrence of search string replaced with
replacement string. Refer the online documentation for more detail.
KING KxNG
BLAKE BLAKE
CLARK CLARK
JONES JONES
MARTIN MARTxN
ALLEN ALLEN
TURNER TURNER
JAMES JAMES
WARD WARD
FORD FORD
SMITH SMxTH
SCOTT SCOTT
ADAMS ADAMS
MILLER MxLLER
Instring
6
Page 47 of 91
DBMS/SQL+
JOINS make it possible to select data from more than one table by means of
a single statement.
If the same table is used more than once in a FROM clause then to resolve
conflicts and ambiguities aliases are used. They are also called co-relation
names or range variables. Once aliases are used, table names cannot be
used in further clauses.
Table F2
COL1 COL2
----- -----
X 100
Y 200
Page 48 of 91
DBMS/SQL+
Page 49 of 91
DBMS/SQL+
The join is based on the equality of column values in the two tables
(emp.deptno= dept.deptno) and therefore is called an equi-join.
Page 50 of 91
DBMS/SQL+
14 rows selected
TABLE F1
COL1 COL2
----- -----
A 1
B 2
C 3
In the above query the join is taken between the rows of the same table so it
also becomes a self-join.
To get the names and salaries of all employees who have managers along with
manager’s name and managers salary.
SQL> SELECT a.ename name , a.sal salary , b.ename mgr, b.sal " Mgr
Salary" FROM emp a , emp b WHERE A.mgr = B.empno;
Page 51 of 91
DBMS/SQL+
This can be avoided by taking an outer join. Outer Join is an exclusive union
of sets (whereas normal joins are intersection). Outer Joins can be
simulated using UNIONS.
In a join of two tables an outer join may be for the first table or the second
table. If the outer join is taken on say the dept table then each row of dept
table will be selected at least once whether or not a join condition is
satisfied.
The general syntax is
Page 52 of 91
DBMS/SQL+
WHERE emp.deptno(+)=dept.deptno
GROUP BY dept.deptno,dept.dname,dept.loc;
Suppose there were any employees without deptno assigned to it. If we take
the equi-join then employees without any dept will not be selected because join
condition will not be satisfied for NULL values. To solve this problem we have
to take an outer join on the department table.
The query to get all the names, salary, department names of all employees we
have to take an outer join on employee table.
3.2. Subqueries
When the WHERE clause needs a set of values which can be only obtained from
another query, the subquery is used. In the WHERE clause it can become a part
of the following predicates
• COMPARISON Predicate
• IN Predicate
• ANY or ALL Predicate
• EXISTS Predicate
Page 53 of 91
DBMS/SQL+
BLAKE 2850
TURNER 1500
JAMES 950
The first select statement is called as OUTER QUERY or MAIN QUERY. The second
SELECT statement is called INNER QUERY or SUB-QUERY. All the rules, which
apply to the main query, also apply to the sub-query. The inner query is
executed FIRST and ONLY ONCE. The inner query returns a single value, namely
30. This value is used to evaluate the main query. Notice that the table used in
inner query can be different from the table used in outer query.
When no data is needed from the outer query, the sub-query is evaluated only
once. The sub-query is executed and the result set is obtained. Such a sub-query
is called as non co-related sub-query.
The sub-query should result in one value of the same data type as the left-
hand side.
To get all the employees whose salary is greater than the average salary of
the company.
ENAME SAL
---------- ----------
CLARK 2450
BLAKE 2850
JONES 2975
SCOTT 3000
FORD 3000
KING 5000
Page 54 of 91
DBMS/SQL+
The datatypes must be comparable to the left and right hand side. The sub-
query generates a list of values of the same type as the <EXPRESSION> on the
left and the operator is any comparison operator.
Page 55 of 91
DBMS/SQL+
3. False if the comparison is false for every value of the list of values
generated by the sub-query.
3 rows selected.
To select the employees whose sal is greater than the sal of all the employees
working in deptno 30.
ENAME SAL
------------ ----------
JONES 2975
SCOTT 3000
KING 5000
FORD 3000
Page 56 of 91
DBMS/SQL+
Here two sets of rows of EMP table will be created one for the outer query and
one for the inner query. In the first pass all the rows of the second set will be
compared with first row of first set. This process will be repeated for all the
rows of the first set. If for each comparison the condition becomes true then
the row from the first set will be selected.
<Query> WHERE
EXISTS < sub-query>
Query will be evaluated if EXISTS takes a value TRUE. It takes the Value TRUE if
the <sub-query> result table is non null and FALSE if it is Null. It is mostly used
with Co-Related Subqueries. EXISTS does not check for a particular value. It
checks whether subquery returns rows or not which match to outer query
rows.
To list all details of dept which has at east one employee assigned to it.
Here there are 4 rows in dept table so the Inner Query will be executed 4 times
for each row returned by outer query. Since there are no employees for deptno
40 the sub-query will return no rows i.e. a null set. Hence EXISTS will become
false and the outer query will not select the row in dept table with value 40.
Page 57 of 91
DBMS/SQL+
4. Advanced SQL
4.1. Index
Index is a database object, which speeds up access to the data. There are
different types of index, which the user can create.
CREATE [UNIQUE] INDEX index_name
ON table_name(col_name1 [ASC|DESC],col_name2,.....);
Example :
CREATE INDEX emp_sal_index ON emp(sal);
• To allow only unique values in ename field, the create statement will
be,
4.2. Synonym
Synonyms are objects, which contain a duplicate name of an existing object.
Page 58 of 91
DBMS/SQL+
4.3. Sequence
Sequence is an object, which can be used to generate sequential numbers.
The numbers, which are generated using a sequence, are usually used to fill
up columns that are declared as UNIQUE or PRIMARY KEY columns.
CREATE SEQUENCE s1
INCREMENT BY 1
START WITH 1
MAXVALUE 10000
NOCYCLE ;
s1 will generate NUMBERs 1,2,3....10000 and stop.
The NUMBER generated by s1 can be used to fill empno column of emp table.
4.4. View
View is a logical table based on one or more tables.
Page 59 of 91
DBMS/SQL+
There are certain restrictions on queries, which can be used to create a view. The
restrictions will be explained when queries are dealt with.
Updation /Insertion of rows in the base table using views is possible only if the
view is based on a single table with some restrictions. The restrictions are:
1. Updation /Insertion Not possible if view is based on two tables. Can be done
in ORACLE 8 by using INSTEAD OF trigger.
2. Insertion is not allowed if the underlying table has any not NULL columns
that do not appear in the view.
3. Insertion/Updation is not allowed if any column of the view referenced in
update/Insert contains functions or calculations.
4. Insertion/Updation /deletion not allowed if view contains group by or
distinct clause in the query.
Page 60 of 91
DBMS/SQL+
5. PL/SQL
5.1. Introduction to PL/SQL
Procedural Language (PL/SQL) is a procedural extension to SQL, provided by
ORACLE. Through PL/SQL, the data manipulation capabilities of SQL are
combined with the processing capabilities of a procedural language. (Pro * C,
Pro * COBOL).
The basic unit in any PL/SQL program is a block, which can occur
sequentially (one after the other) or nested (One inside the other).
Named blocks are anonymous blocks with a label that gives the block a
name. They are also constructed dynamically and executed only once.
Subprograms are procedures, packages and functions that are stored in the
database. These blocks generally don’t change once they are constructed
and are executed many times by calling them explicitly via a call to a
procedure, package or function.
TRIGGERS are named blocks that are stored in the database. They are
executed implicitly whenever the triggering event occurs. The triggering
event is a DML statement executed against a table in the database.
Page 61 of 91
DBMS/SQL+
Output
SQL> /
PL/SQL procedure successfully completed.
Example 5.1
Declaration section is where all the variables and cursors used in a block are
declared. Execution section has SQL statements and PL/SQL constructs which
aid in BRANCHING, LOOPING and CONDITIONAL EXECUTION. Exception
section has statements, which handle the exceptions.
Page 62 of 91
DBMS/SQL+
DECLARE
V_Description VARCHAR2(25) ;
V_Sal NUMBER(5) NOT NULL := 3000 ;
V_Compcode VARCHAR2(20) CONSTANT := 'ABC CONSULTANTS' ;
V_Comm NOT NULL DEFAULT 0 ;
PL/SQL Datatypes
Page 63 of 91
DBMS/SQL+
This can hold a numeric value, either integer or floating point. It is same
as the number database type.
2. BINARY_INTEGER
If a numeric value is not to be stored in the database, the
BINARY_INTEGER datatype can be used. It can only store integers from -
2147483647 to + 2147483647. Mostly used for counter variables.
V_Counter BINARY_INTEGER DEFAULT 0 ;
3. VARCHAR2(L)
L is necessary and is max length of the variable. This behaves like
VARCHAR2 database type. The maximum length in PL/SQL is 32,767
bytes where as VARCHAR2 database type can hold max 2000 bytes. If a
VARCHAR2 PL/SQL column is more than 2000 bytes, it can only be
inserted into a database column of type LONG .
4. CHAR(L)
Here L is the maximum length. Specifying length is optional. If not
specified it defaults to 1. The maximum length of CHAR PL/SQL variable
is 32,767 bytes whereas that of database CHAR column is 255 bytes.
Therefore a CHAR variable of more than 255 bytes can be inserted in the
database column of VARCHAR2 or LONG type.
5. LONG
PL/SQL LONG type is just 32,767 bytes. It behaves similar to LONG
DATABASE type.
6. DATE
The DATE PL/SQL type behaves the same way as the date database
type. The DATE type is used to store both date and time. A DATE
variable is 7 bytes in PL/SQL.
7. BOOLEAN
A Boolean type variable can only have one of 2 values either TRUE or
FALSE. They are mostly used in control structures.
V_Does_Dept_Exist BOOLEAN := TRUE ;
V_ Flag BOOLEAN := 0 ; -- illegal
Page 64 of 91
DBMS/SQL+
USING %TYPE
%TYPE is used to declare a variable with the same datatype as a column of a
specific table.
Var_Name table_name.col_name%TYPE ;
V_Empno emp.empno%TYPE ;
Datatype of V_Empno is same as that of Empno column of the EMP table.
USING %ROWTYPE
%ROWTYPE is used to declare a compound variable whose type is same as that
of a row of a table.
Var_Name table_name%ROWTYPE ;
V_Emprec emp%ROWTYPE ;
Page 65 of 91
DBMS/SQL+
<<Outer>>
DECLARE
v_NAME VARCHAR2(10);
v_SSN NUMBER(9);
BEGIN V_NAME and the NUMBER(9) v_SSN are visible
À
DECLARE
v_SSN CHAR(11);
v_FLAG VARCHAR2(10); v_Flag, and the CHAR(11) v_SSN are visible. But
BEGIN we can refer to the NUMBER(9)v_SSN with
Á IOuter.v_SSN
END;
 V_NAME and the NUMBER(9) v_SSN are visible
END;
SQL IN PL/SQL
SELECT STATEMENT
SELECT Column_List INTO Variable_List
FROM Table_List
[WHERE expr1]
[CONNECT BY expr2 [START WITH expr3]]
[GROUP BY expr4] [HAVING expr5]
[UNION | INTERSECT | MINUS SELECT ...]
[ORDER BY expr | ASC | DESC]
[FOR UPDATE [OF Col1,...] [NOWAIT]]
INTO Variable_List
This clause is used if the selected row must be modified through a DELETE or
UPDATE command. Since the contents of the row must not be modified between
the SELECT command and the UPDATE command, it is necessary to lock the row
after the SELECT command. FOR UPDATE will lock the selected row. OF Col1,
lists the columns, which can be modified by the UPDATE command. If OF
Col1,... is missing, all the columns can be modified.
Page 66 of 91
DBMS/SQL+
DECLARE
V_Emprec emp%ROWTYPE;
V_Ename emp.ename%TYPE;
V_Sal emp.sal%TYPE;
BEGIN
SELECT * INTO V_Emprec FROM emp WHERE ename ='SMITH';
SELECT ename,sal INTO V_Ename,V_Sal from emp where ename ='SMITH';
END;
Example 5.2
INSERT STATEMENT
The syntax for the insert statement remains the same as in SQL –INSERT.
DECLARE
V_Dname VARCHAR2(15) := 'FINANCE';
BEGIN
INSERT INTO dept VALUES ( 50 , V_Dname, 'BOMBAY');
END;
/
Example 5.3
DELETE STATEMENT
DELETE FROM table_name
WHERE [CURRENT OF Cursor_Name|Condition]
DECLARE
V_Sal_Cutoff NUMBER(4):= 2000;
BEGIN
DELETE FROM emp WHERE sal < V_Sal_Cutoff;
END;
/
Example 5.4
UPDATE STATEMENT
UPDATE table_name SET col_name = Value
WHERE [CURRENT OF Cursor_Name|Condition]
DECLARE
V_Sal_Incr NUMBER(5) := 1000;
BEGIN
UPDATE emp SET sal = sal + V_Sal_Incr WHERE ename='SMITH';
END;
/
Example 5.5
Page 67 of 91
DBMS/SQL+
VARIABLE NAMES
Consider the block
DECLARE
V_Deptno NUMBER(10) := 30;
V_Dname VARCHAR2(15) ;
BEGIN
SELECT dname INTO V_Dname FROM dept WHERE deptno = V_Deptno;
END;
Example 5.6
Here there is no ambiguity between the database column names and PL/SQL
variables.
DECLARE
Deptno NUMBER(10) := 30;
V_dname VARCHAR2(15) ;
BEGIN
SELECT dname INTO V_dname FROM dept WHERE deptno = deptno;
DELETE FROM dept WHERE deptno = deptno ;
END;
Example 5.7
Here the select statement will select names of all the departments and not only
deptno. 30. The delete statement will delete all the employees. This happens
because when the PL/SQL engine sees a condition expr1 = expr2, expr1 and
expr2 are first checked to see whether they match the database columns first
and then the PL/SQL variables. So in above example deptno = deptno both are
treated as database columns and the condition will become true for every row
of the table.
If a block has a label then variables with same names as database columns can
be used by using <<blockname>>. Variable_Name notation.
<<BLOCK1>>
DECLARE
Deptno NUMBER(10) := 30;
Dname VARCHAR2(15) ;
BEGIN
SELECT Dname INTO dname FROM dept WHERE deptno = Block1. deptno;
DELETE FROM dept WHERE deptno = Block1. deptno ;
END;
Example 5.8
Page 68 of 91
DBMS/SQL+
Although this method can be used to get the desired results, it is not a good
programming practice to use same names for PL/SQL variables and database
columns.
DECLARE
V_Counter NUMBER := 50 ;
BEGIN
LOOP
INSERT INTO dept
VALUES(V_Counter,'NEW DEPT','SOMEWHERE');
V_Counter := V_Counter + 10 ;
END LOOP;
COMMIT ;
END ;
/
Example 5.13
This is an endless loop. When LOOP ENDLOOP is used in the above format,
then an exit path must necessarily be provided. Exit path is provided using
EXIT or EXIT WHEN commands.
BEGIN
.....
LOOP
IF <Condition> THEN
. . . . .
EXIT ; -- Exits loop immediately
END IF ;
END LOOP;
. . . . . -- Control resumes here
COMMIT ;
END ;
/
Page 69 of 91
DBMS/SQL+
DECLARE
V_Counter NUMBER := 50 ;
BEGIN
LOOP
INSERT INTO dept
VALUES(V_Counter,'NEWDEPT','SOMEWHERE') ;
DELETE FROM emp WHERE deptno = V_Counter ;
V_Counter := V_Counter + 10 ;
EXIT WHEN V_Counter >100 ;
END LOOP;
COMMIT ;
END ;
/
Example 5.14
As long as V_Counter has a value less than or equal to 100, the loop
continues.
LOOP…END LOOP can be used in conjunction with FOR and WHILE for better
control on looping.
The syntax of FOR LOOP is
FOR loop is used for executing the loop a fixed number of times. The number
of times the loop will execute equals
Upper_Bound - Lower_Bound + 1.
Upper_Bound and Lower_Bound must be integers and Upper_Bound must be
equal to or greater than Lower_Bound. Variables in FOR loop need not be
explicitly declared. Variables take values starting at a Lower_Bound and
ending at a Upper_Bound. The variable value is incremented by 1, every
time the loop reaches the bottom. When the variable value becomes equal
to the Upper_Bound then the loop executes and exits.
Page 70 of 91
DBMS/SQL+
DECLARE
V_Counter NUMBER := 50 ;
BEGIN
FOR Loop_Counter IN 2..5
LOOP
INSERT INTO dept
VALUES(V_Counter,'NEW DEPT','SOMEWHERE') ;
V_Counter := V_Counter + 10 ;
END LOOP;
COMMIT ;
END ;
Example 5.15
The loop will be executed (5 - 2 + 1) = 4 times. A Loop_Counter variable can
also be used inside the loop, if need be. Lower_Bound and/or Upper_Bound
can be integer expressions also.
The syntax for the WHILE LOOP is
WHILE Condition
LOOP
PL/SQL Statements;
END LOOP;
EXIT OR EXIT WHEN can be used inside the while loop to exit the loop
prematurely.
BEGIN
<<Outer_Loop>>
LOOP
PL/SQL
<< Inner_Loop>>
LOOP
PL/SQL Statements ;
EXIT Outer_Loop WHEN <Condition Met>;
END LOOP Inner_Loop;
END LOOP Outer_Loop;
END ;
/
Example 5.16
Page 71 of 91
DBMS/SQL+
IF Condition_Expr THEN
PL/SQL_Statements
End if;
When the condition evaluates to TRUE then the PL/SQL statements are
executed, otherwise the statement following END IF is executed.
IF Condition_Expr THEN
PL/SQL_Statements_1 ;
ELSE
PL/SQL_Statements_2 ;
END IF;
IF Condition_Expr_1 THEN
PL/SQL_Statements_1 ;
ELSIF Condition_Expr_2 THEN
PL/SQL_Statements_2 ;
ELSIF Condition_Expr_3 THEN
PL/SQL_Statements_3 ;
ELSE
PL/SQL_Statements_n ;
END IF;
Page 72 of 91
DBMS/SQL+
As every condition must have at least one statement, NULL statement can be
used as filler. NULL command does nothing. Sometimes NULL is used in a
condition merely to indicate that such a condition has also been taken into
consideration. So your code will resemble the code as given below:
IF Condition_Expr_1 THEN
PL/SQL_Statements_1 ;
ELSIF Condition_Expr_2 THEN
PL/SQL_Statements_2 ;
ELSIF Condition_Expr_3 THEN
Null;
END IF;
CONDITIONS FOR NULL are checked through IS NULL and IS NOT NULL
predicates.
Page 73 of 91
DBMS/SQL+
6. Error Handling
A good programming language should provide capabilities of handling errors and
recovering from them if possible. PL/SQL implements error handling via
exceptions and exception handlers.
DECLARE
E_Balance_Not_Sufficient EXCEPTION;
E_Comm_Too_Large EXCEPTION;
…
BEGIN
NULL;
END;
Page 74 of 91
DBMS/SQL+
TOO_MANY_ROWS
This is raised when SELECT INTO …. Statement returns more than one row.
INVALID_CURSOR
This is raised when an illegal cursor operation is performed such as closing an
already closed cursor.
VALUE_ERROR
This exception is raised when an arithmetic, conversion, truncation or
constraint error occurs in a procedural statement.
DUP_VAL_ON_INDEX
This is raised when the UNIQUE CONSTRAINT is violated.
Raising Exceptions
When the error associated with an exception occurs, the exception is raised.
This is done through the RAISE command. The syntax is
RAISE Exception_Name ;
An exception is defined and raised as shown below:
DECLARE
...
Retired_Emp EXCEPTION ;
BEGIN
PL/SQL_Statements ;
IF Error_Condition THEN
RAISE Retired_Emp ;
PL/SQL_Statements ;
END IF;
EXCEPTION
WHEN Retired_Emp THEN
PL/SQL_Statements ;
END ;
Page 75 of 91
DBMS/SQL+
DECLARE
Dup_Deptno EXCEPTION;
V_Counter BINARY_INTEGER;
V_Department NUMBER(2) := 50;
BEGIN
SELECT COUNT(*) INTO V_Counter FROM Dept WHERE deptno = 50;
IF V_Counter > 0 THEN
RAISE Dup_Deptno ;
END IF;
INSERT INTO dept VALUES (V_Department ,'NEW NAME', 'NEW LOC');
EXCEPTION
WHEN Dup_Deptno THEN
INSERT INTO Error_Log VALUES ('Department ' || V_Department
|| ' IS ALREADY PRESENT');
END ;
/
Example 6.1
OTHERS exception handler
The OTHERS handler will execute for all raised exceptions. It should always be
the last handler in the block. The OTHERS exception handler handles all errors,
which are not handled separately in the EXCEPTION section. To handle a
specific case within the OTHERS handler, predefined functions SQLCODE and
SQLERRM are used.
SQLCODE returns the current error code. And SQLERRM returns the current
error message text. The values of SQLCODE and SQLERRM should be assigned to
local variables before using it within a SQL statement.
DECLARE
Err_Num NUMBER ;
Err_Msg CHAR(100);
BEGIN
-------
------
EXCEPTION
----------
-------
WHEN OTHERS THEN
-- Assign values to variables. SQLCODE SQLERRM cannot be used
directly.
Err_Num = SQLCODE ;
Err_Msg =SUBSTR( SQLERRM, 1, 100);
-- Errors is a table existing in the database created by the user
INSERT INTO errors VALUES( Err_Num, Err_Msg );
END;
/
Page 76 of 91
DBMS/SQL+
DECLARE
V_Deptno NUMBER(2):= 10;
BEGIN
DELETE FROM dept WHERE deptno = V_Deptno ;
EXCEPTION
WHEN OTHERS THEN
/* Error -2292 OCCURS WHEN REFERENTIAL INTEGRITY RULE
IS VIOLATED */
IF SQLCODE = - 2292 THEN
/* Error_Log is a table containing one varchar2 column
created by user to store error messages */
INSERT INTO Error_Log
VALUES('Employees exist for Department No' || V_Deptno);
ELSE
INSERT INTO Error_Log
VALUES('Unable to delete dept No' || V_Deptno ||'because
of unknown reasons');
END IF ;
END ;
/
DECLARE
V_Dummy VARCHAR2(1);
V_Department NUMBER(2) := 50;
BEGIN
SELECT 'X' INTO V_Dummy FROM dept WHERE Deptno= V_Department;
INSERT INTO Error_Log
VALUES ('Department ' || V_Department || 'IS ALREADY PRESENT');
EXCEPTION
WHEN NO_DATA_FOUND THEN
INSERT INTO dept
VALUES (V_Department ,'NEW NAME', 'NEW LOC');
END ;
/
Example 6.2
Page 77 of 91
DBMS/SQL+
Anonymous blocks are executed by interactively entering the block at the SQL>
prompt OR by writing the PL/SQL statements in a user-named file and executing
the block at SQL> prompt using @ command. The block needs to be compiled
every time it is run and only the user who created the block can use the block.
Stored subprograms are named PL/SQL blocks. Stored subprograms are compiled
at the time of creation and stored in the database itself. The source code is also
stored in the database. Any user with necessary privileges can use the stored
subprogram. Stored subprogram come in handy during application development.
Stored subprograms can be executed from the SQL> prompt using EXECUTE
command. The syntax is
7.1. Procedure
CREATE PROCEDURE Proc_Name
(Parameter {IN | OUT | IN OUT} datatype := value,...) AS
Variable_Declaration ;
Cursor_Declaration ;
Exception_Declaration ;
BEGIN
PL/SQL_Statements ;
EXCEPTION
Exception_Definition ;
END Proc_Name ;
Page 78 of 91
DBMS/SQL+
If a parameter is defined as IN, then the calling program can only pass the value
to the procedure. It cannot be on the left-hand side of the assignment operator.
A parameter defined as OUT is used to return a value to the caller. Any number
of OUT parameters can be passed. Any OUT parameter cannot be on the right
hand side of the assignment operator.
IN OUT IN OUT
Page 79 of 91
DBMS/SQL+
Page 80 of 91
DBMS/SQL+
Example 7.2
Now consider the following calls to Create_Dept
BEGIN
Create_Dept( 50);
-- Actual call will be Create_Dept ( 50, 'TEMP', 'TEMP')
Create_Dept ( 50, 'FINANCE');
-- Actual call will be Create_Dept ( 50, 'FINANCE' ,'TEMP')
Create_Dept( 50, 'FINANCE', 'BOMBAY') ;
-- Actual call will be Create_Dept(50, 'FINANCE', 'BOMBAY' )
END;
END;
Example 7.4
Page 81 of 91
DBMS/SQL+
Example 7.5
7.2. Functions
Functions are similar to procedures. They can accept one or more
parameters and return a single value by using a return value. Functions can
return multiple values by using OUT parameters. Functions are used as part
of an expression and can be called as
Lvalue =Function_Name( Param1, Param2, …….)
Functions returning a single value for a row can be used with SQL
statements.
Syntax of a FUNCTION:
Page 82 of 91
DBMS/SQL+
Example 7.7
Create a bind variable Avgsalary in SQLPLUS using VARIABLE command as
follows
SQL> VARIABLE Avgsalary NUMBER
Execute the Function by executing the following PL/SQL block.
Page 83 of 91
DBMS/SQL+
BEGIN
:Avgsalary := Get_Avg_Sal ( 50);
END ;
/
After execution use the SQL*PLUS PRINT command to see the results
PRINT Avgsalary
7.3. Packages
Packages are PL/SQL constructs that allow related objects to be stored
together.
PACKAGE BODY contains the function and procedure definitions, which are
declared in the PACKAGE SPECIFICATION. The PACKAGE BODY is optional. If
the package specification does not contain any procedures or functions and
contains only variable and cursor declarations then the body need not be
present
Page 84 of 91
DBMS/SQL+
where
Page 85 of 91
DBMS/SQL+
Example 7.9
Page 86 of 91
DBMS/SQL+
BEGIN
Emp_Actions.New_Employee( 10, 'ABCD', …….);
V_Sal := Emp_Actions. Get_Sal( 7566);
END ;
The first time a package is called, it is instantiated. This means that the
package is read from disk into memory and P-CODE is run. At this point
memory is allocated for any variables defined in the package. Each session
will have its own copy of packaged variables, so there is no problem of two
simultaneous sessions accessing the same memory locations.
Page 87 of 91
DBMS/SQL+
8. Table of Examples
Figure 1-1 DBMS Structure ..............................................................3
Figure 1-2 Relational Tables...........................................................7
Example 5.1.........................................................................................62
Figure 5-1 Datatypes ...........................................................................63
Example 5.2 ..........................................................................................67
Example 5.3 ..........................................................................................67
Example 5.4 ..........................................................................................67
Example 5.5 ..........................................................................................67
Example 5.6 ..........................................................................................68
Example 5.7 ..........................................................................................68
Example 5.8 ..........................................................................................68
Example 5.13........................................................................................69
Example 5.14........................................................................................70
Example 5.15......................................................................................71
Example 5.16........................................................................................71
Example 6.1........................................................................................76
Example 6.2........................................................................................77
Example 7.1........................................................................................80
Example 7.2........................................................................................81
Page 88 of 91
DBMS/SQL+
9. Appendix A
Guidelines for Good SQL:
• Avoid using arithmetic expressions or functions on the left hand side of the
SELECT criteria (as in WHERE clause) that involves a column name; since it
will not use index.
• '[NOT] EXISTS' should be used rather than '[NOT] IN' when using a subquery
that tests existence or absence of a row.
• To use an index, the columns in the WHERE clause should be ordered in the
order they appear on the desired index.
• When using more than one table on a FROM clause, the table that is having
the larger number of rows should be listed first.
• When using an '... IN' clause, the elements in the subset (,,,) should be
listed in alphabetical order.
• When poor performance exists with very complex joins, the UNION clause
should be used instead of a normal join, whenever possible.
• For numeric columns that allow nulls, NVL function should be used
Page 89 of 91
DBMS/SQL+
10. Appendix B
Dept Table
Name Type
DEPTNO NUMBER(2)
DNAME VARCHAR2(14)
LOC VARCHAR2(13)
Emp Table
Name Type
EMPNO NUMBER(4)
ENAME VARCHAR2(10)
JOB VARCHAR2(9)
MGR NUMBER(4)
HIREDATE DATE
SAL NUMBER(7,2)
COMM NUMBER(7,2)
DEPTNO NUMBER(2)
Page 90 of 91
DBMS/SQL+
Page 91 of 91