DBMS Lab Manual
DBMS Lab Manual
opasdfghjklzxcvbnmqwertyuiopasdfgh
jklzxcvbnmqwertyuiopasdfghjklzxcvb
nmqwertyuiopasdfghjklzxcvbnmqwer
tyuiopasdfghjklzxcvbnmqwertyuiopas
Reference Manual
dfghjklzxcvbnmqwertyuiopasdfghjklzx
cvbnmqwertyuiopasdfghjklzxcvbnmq
for
wertyuiopasdfghjklzxcvbnmqwertyuio
Database Systems Lab
pasdfghjklzxcvbnmqwertyuiopasdfghjk
School of Computing Science and Engineering
lzxcvbnmqwertyuiopasdfghjklzxcvbnm
qwertyuiopasdfghjklzxcvbnmqwertyuio
pasdfghjklzxcvbnmqwertyuiopasdfghj
klzxcvbnmqwertyuiopasdfghjklzxcvbn
mqwertyuiopasdfghjklzxcvbnmrtyuio
Vellore‐632014,Tamil Nadu
pasdfghjklzxcvbnmqwertyuiopasdfghj 1
klzxcvbnmqwertyuiopasdfghjklzxcvbn
CONTENTS
2. CONSTRAINTS 15
3. OPERATORS IN SQL*PLUS 23
5. JOINS 35
6. VIEWS 47
7. PL/SQL 52
10 CURSORS 78
11 EXCEPTIONS 85
13 PACKAGES 98
14 TRIGGERS 103
3
SQL STATEMENTS
SQL statements are classified as follows:
Data Retrieval Statement:
SELECT is the data extracting statement which retrieves the data from the database.
Data Manipulation Language (DML):
This language constitutes the statements that are used to manipulate with the data. It has
three commands, which are INSERT, UPDATE and DELETE.
Data Definition Language (DDL):
This is the language used to define the structure of the tables. It sets up, changes, and
removes data structures from the tables. It uses 5 commands, which are CREATE, ALTER,
DROP, RENAME and TRUNCATE.
Data Transaction Language (DTL):
This is the language used to do undo and redo the transaction performed in the database.
The commands are Commit, Rollback, and Save Point
Data Control Language:
This language is used to sanction the rights to the users to use the other user’s database
objects. The commands are Grant and Revoke
Consider the following schema based on which the example queries are discussed in this manual.
BASE SCHEMA
EMPLOYEE
Name Type
-------------------------- ----------------------
EMPLOYEE_ID NUMBER(3)
FIRST_NAME VARCHAR2(10)
LAST_NAME VARCHAR2(10)
MGR NUMBER(4)
HIRE_DATE DATE
JOB_ID VARCHAR2(10)
SALARY NUMBER(10)
COMMISION NUMBER(8)
DEPTNO NUMBER(2)
4
DEPARTMENT
Name Type
--------------- -----------------
DEPTNO NUMBER(2)
DNAME VARCHAR2(14)
LOC VARCHAR2(13)
BONUS
Name Type
---------------- -------------------
ENAME VARCHAR2(10)
JOB VARCHAR2(9)
SAL NUMBER(10,2)
COMM NUMBER(10)
JOBGRADE
Name Type
----------------- ---------------------
JOB_ID VARCHAR2(10)
GRADE NUMBER
LOSAL NUMBER
HISAL NUMBER
5
1. a. Creating a table
Syntax:
Create table <Table Name>
( <Field1> <Data Type> <(width) <constraints> ,
<Field2> <Data Type> <(width)> <constraints>,
..................................);
Example:
6
( employee_id number(3),
first_name varchar2(10),
last_name varchar2(10),
mgr number(4),
hire_date date,
job_id varchar2(10),
salary number(10),
commision number(8),
deptno number(2));
Output:
Table created.
Example:
(deptno number(2),
dname varchar(14),
loc varchar(13));
Output:
Table created.
Note:
FIRST_NAME VARCHAR2(10)
LAST_NAME VARCHAR2(10)
MGR NUMBER(4)
HIRE_DATE DATE
JOB_ID VARCHAR2(10)
SALARY NUMBER(10)
COMMISION NUMBER(8)
DEPTNO NUMBER(2)
2. Alter Table Statement:
Alter command is used to perform the following action on the table:
a. Adding column in the existing table
b. Increasing and decreasing the column size and changing data types
c. Dropping column
d. Renaming the column
e. Adding and dropping constraints to the table( discussed in constraints topics)
f. Enabling & disabling constraints in the table( discussed in constraints topics)
a. To Add a column to the table (structure)
Add option is used to add a new column
Syntax:
Alter Table <Table-Name> Add <Field Name> <Type> (width);
Example:
SQL> alter table employee add address varchar2 (20);
Output:
Table altered.
b. To Modify a field of the table
Syntax:
Alter Table <tablename> MODIFY ( <column name > < newdatatype>);
Example:
SQL> alter table employee modify address varchar2 (10);
Output:
Table altered.
c. To Drop a field of the table
Drop option is used to delete a column or remove a constraint
Syntax:
Alter Table <tablename> DROP COLUMN < column name>;
Example:
SQL> alter table employee drop column address;
Output:
Table altered.
d.To rename a column
Syntax:
ALTER TABLE <tablename> RENAME COLUMN <oldcolumnname> TO
<newcolumn name>
Example:
SQL> alter table employee rename column mgr to manager;
Output:
Table altered.
• To Drop a table - Deletes a Table along with all contents
Syntax:
Drop Table <Table-Name>;
Example:
Drop Table Student_table;
Output:
Table Dropped
9
• To Truncate a table - Deletes all rows from a table ,retaining its structure
Syntax: Truncate Table <tablename>
Example:
SQL> truncate table employee;
Output:
Table truncated.
g. To rename a table- Renames a table with new name
Syntax:
Rename <oldtablename> To <newtablename>
Example:
SQL> rename employee to emp;
Output:
Table renamed
Output:
1 row created.
c. Inserting interactively(Inserting ,ultiple rows by using single insert command)
Syntax:
Insert Into <tablename> Values( &<column name1> , &<column name2> …);
Example:
SQL> insert into employee values(&empid,'&fn','&ln',&mgr,'&hdate','&job',&sal,
&comm,&dept);
Enter value for empid: 111
Enter value for fn: Smith
Enter value for ln: Ford
Enter value for mgr: 222
Enter value for hdate: 21-jul-2010
Enter value for job: J1
Enter value for sal: 30000
Enter value for comm: 0.1
Enter value for dept: 10
old 2: &comm,&dept)
new 2: 0.1,10)
Output:
1 row created.
Note: Column names of character and date type should be included with in single quotation.
• Inserting null values
Syntax:
Insert Into <tablename> Values ( val1,’ ‘,’ ‘,val4);
Example:
insert into department values( ‘101’,’’,chennai);
Output:
1 row created.
2. To Delete rows from a table
11
Syntax:
Delete from <table name> [where <condition>];
Example:
a) to delete all rows:
SQL> delete from department;
Output:
89 rows deleted.
b) conditional deletion:
SQL> delete from department where loc='chennai';
Output:
1 row deleted.
3. Modifying (Updating) Records:
a. Updating single column
Syntax:
UPDATE <table name> Set <Field Name> = <Value> Where <Condition>;
Example:
SQL> update department set loc='Hyderabad' where deptno=20;
Output:
1 row updated.
Note: Without where clause all the rows will get updated.
b. Updating multiple column [while updating more than one column, the column must be
separated by comma operator]
Example: SQL> update department set loc='Hyderabad', dname= ‘cse’ where deptno=20;
Output:
1 row updated.
4. Selection of Records [Retrieving (Displaying) Data:]
Syntax:
Select <field1, field2 …fieldn> from <table name> where <condition>;
Example:
a) SQL> select * from department;
12
Output:
DEPTNO DNAME LOC
---------- -------------- -------------
10 accounts chennai
20 finance Hyderabad
30 IT Bangalore
40 marketing chennai
Example:
b) SQL> select dname, loc from department;
Output:
DNAME LOC
-------------- -------------
accounts chennai
finance Hyderabad
IT Bangalore
marketing Chennai
• With distinct clause [Used to retrieve unique value from the column]
Syntax:
Select distinct <col2> from < tab1>;
Example:
SQL> select distinct loc from department;
Output:
13
LOC
-------------
chennai
Bangalore
Hyderabad
Output:
Name Null? Type
----------------------------------------- -------- -----------------
EMPLOYEE_ID NUMBER(3)
FIRST_NAME VARCHAR2(10)
LAST_NAME VARCHAR2(10)
MANAGER NUMBER(4)
HIRE_DATE DATE
JOB_ID VARCHAR2(10)
SALARY NUMBER(10)
COMMISION NUMBER(8)
DEPTNO NUMBER(2)
Note: Only structure of table alone is copied and not the contents.
Example:
SQL> insert into copyofemp2 (select * from employee where employee_id > 100);
Output:
50 rows created.
Constraints
• Constraints enforce rules on the table whenever rows are inserted, updated and deleted
from the table.
• Prevents the deletion of a table if there are dependencies from other tables.
• Name a constraints or the oracle server generate name by using SYS_cn format.
• Define the constraints at column or table level. constraints can be applied while creation
of table or after the table creation by using alter command.
15
Constraints Types
CONSTRAINT DESCRIPTION
PRIMARY KEY Specifies a column or a set of columns that uniquely identifies as row.
It does not allow null values.
CHECK Specifies a condition that must be satisfied by all the rows in a table.
Syntax:
16
Syntax:
CREATE TABLE < tablename1> (
<column name 1> < datatype> CONSTRAINT <constraint name1> UNIQUE,
<column name 2> < datatype> CONSTRAINT <constraint name2> NOT NULL,
constraint < constraint name3 > PRIMARY KEY ( <column name1>),
constraint <constraint name4> FOREIGN KEY (<column name2>)
REFERENCES <tablename2> (<column name1>)
);
Example:
CREATE TABLE emp_demo3
( employee_id NUMBER(6) CONSTRAINT emp_eid PRIMARY KEY,
first_name VARCHAR2(20),
last_name VARCHAR2(25) CONSTRAINT emp_last_name_nn NOT NULL,
email VARCHAR2(25) CONSTRAINT emp_email_nn NOT NULL,
phone_number VARCHAR2(20),
job_id VARCHAR2(10) CONSTRAINT emp_job_nn NOT NULL,
17
Syntax:
CREATE TABLE < tablename> (
<column name1 > < datatype> ,
<column name 2> < datatype>,
CHECK ( < column name 1 > in ( values) )
CHECK ( < column name 2 > between <val1> and <val2> ) );
Example:
CREATE TABLE emp_demo4
( emp_id NUMBER(6),
emp_name VARCHAR2(15),
salary NUMBER(10) CHECK (salary between 1000 and 10000)
);
Adding Constriants
Constraints can be added after the table creation by using alter command
Examples:
18
Drop Constraints
Syntax
Drop the unique key on the email column of the employees table:
CASCADE Constraints
The CASCADE Constraints clause is used along with the Drop Column Clause.
• A foreign key with a cascade delete means that if a record in the parent table is deleted,
then the corresponding records in the child table will automatically be deleted. This is
called a cascade delete.
• A foreign key with a cascade delete can be defined in either a CREATE TABLE statement or
an ALTER TABLE statement.
Syntax:
19
Operators in SQL*PLUS
Type Symbol / Keyword Where to use
Comparison =, !=, <, <=, >, >=, between, not WHERE clause
between, in, not in, like, not like
20
• Between..And..
Example:
SQL> select first_name, deptno from employee where salary between 20000 and 35000;
Output:
FIRST_NAME DEPTNO
---------- ----------
Smith 10
• IN
Example:
SQL> select first_name, deptno from employee where job_id in ('J1','J2');
Output:
FIRST_NAME DEPTNO
---------- ----------
Smith 10
Arun 30
Nithya 10
• NOT IN
Example:
SQL> select dname,loc from department where loc not in ('chennai','Bangalore');
Output:
DNAME LOC
-------------- -------------
finance Hyderabad
• Like
Use the LIKE condition to perform wild card searches of valid search string values.
21
Example:
SQL> select dname,loc from department where loc like 'c%';
Output:
DNAME LOC
-------------- -------------
accounts chennai
marketing Chennai
Example:
SQL> select dname,loc from department where loc like 'chen_ _ _';
Output:
DNAME LOC
-------------- -------------
accounts chennai
marketing Chennai
Example:
SQL> select dname,loc from department where loc not like 'c%';
Output:
DNAME LOC
-------------- -------------
finance Hyderabad
IT Bangalore
• Between..and..
Example:
SQL> select first_name, deptno, salary from employee where salary not between 20000 and
35000;
Output:
FIRST_NAME DEPTNO SALARY
---------- ---------- ----------
Arun 30 40000
Nithya 10 45000
22
Example:
SQL> insert into department(deptno,dname) values(40,'Sales');
Output:
1 row created.
• is Null
Example:
SQL> select * from department where loc is null;
Output:
DEPTNO DNAME LOC
---------- -------------- -------------
40 Sales
Example:
SQL> select * from department where loc is not null;
Output:
DEPTNO DNAME LOC
---------- -------------- -------------
10 accounts chennai
20 finance Hyderabad
30 IT Bangalore
40 marketing chennai
LOGICAL OPERATORS: Used to combine the results of two or more conditions to produce a
single result. The logical operators are: OR, AND, NOT.
Operator Precedence
• Arithmetic operators-Highest precedence
• Comparison operators
• NOT operator
• AND operator
• OR operator----Lowest precedence
23
Output:
FIRST_NAME DEPTNO SALARY
---------- ---------- ----------
Smith 10 30000
Arun 30 40000
Nithya 10 45000
Example:
SQL> select first_name, deptno, salary from employee
where salary > 20000 and salary < 35000;
Output:
FIRST_NAME DEPTNO SALARY
---------- ---------- ----------
Smith 10 30000
Example:
SQL> select first_name, deptno, salary+100 from employee where salary > 35000;
Output:
FIRST_NAME DEPTNO SALARY+100
---------- ---------- ----------
Arun 30 40100
Example:
SQL> update employee set salary = salary+salary*0.1 where employee_id = 111;
Output:
1 row updated.
Example:
SQL> select * from department where loc = 'chennai' or dname='IT';
24
Output:
DEPTNO DNAME LOC
---------- -------------- -------------
10 accounts chennai
30 IT Bangalore
40 marketing chennai
FUNCTIONS
• Group functions
Returns only one value for every row can be used in SELECT command and included in
WHERE clause
Types
• Character functions
• Numeric functions
• Date functions
CHARACTER FUNCTIONS:
Character functions accept a character input and return either character or number values. Some
of them supported by Oracle are listed below
Syntax Description
25
replace(char, search string, replace string) Replaces the search string to new
lpad(char, length, special char) Pads special char to left of char to Max of
length
rpad(char, length, special char) Pads special char to right of char to Max of
length
Examples:
Function Input Output
Initcap(char) SQL>select initcap(‘hello’) from dual; Hello
Lower(char) SQL>select lower(‘FUN’) from dual; fun
Upper(char) SQL>select upper(‘sun’) from dual; SUN
Ltrim(char, set) SQL>select ltrim(‘xyzhello’,’xyz’) from dual; hello
Rtrim(char, set) SQL>select rtrim(‘xyzhello’,’llo’) from dual; xyzhe
translate(char,from,to) SQL>select translate(‘jack’,’j’,’b’) from dual; back
Replace(char,from,to) SQL>select replace(‘jack and jue’,’ j’, ’bl’) from black and blue
dual;
Example:
SQL> select initcap(dname) from department;
Output:
INITCAP(DNAME)
--------------
Accounts
Finance
It
Marketing
Sales
Lpad is a function that takes three arguments. The first argument is the character string which
has to be displayed with the left padding. The second is the number which indicates the total
26
length of the return value, the third is the string with which the left padding has to be done when
required.
Example:
SQL> select lpad(dname,15,'*') lpd from department;
Output:
LPD
---------------
*******accounts
********finance
*************IT
******marketing
**********Sales
Example:
SQL> select rpad(dname,15,'*') rpd from department;
Output:
RPD
---------------
accounts*******
finance********
IT*************
marketing******
Sales**********
Example:
SQL> select dname || ' is located in ' || loc from department;
Output:
DNAME||'ISLOCATEDIN'||LOC
------------------------------------------
accounts is located in chennai
finance is located in Hyderabad
IT is located in Bangalore
marketing is located in chennai
Sales is located in
NUMERIC FUNCTIONS:
Numeric functions accept numeric input and returns numeric values as output.
Syntax Description
Examples:
28
Example:
SQL> select ln (2) from dual; (returns natural logarithm value of 2)
SQL>select sign (-35) from dual; (output is -1)
Output:
TO_CHAR(HIRE_DATE,'DDT
----------------------
21st of july 2010
05th of june 2008
12th of february 1999
• To_ date ( )
The format is to_date (char [, fmt]). This converts char or varchar data type to date data type.
Format model, fmt specifies the form of character.
Example:
29
ROUND(HIR
---------
01-JAN-11
01-JAN-08
01-JAN-99
• To_ Number( )
Allows the conversion of string containing numbers into the number data type on which
arithmetic operations can be performed.
Example: SQL> select to_number (‘100’) from dual;
DATE FUNCTIONS
Example:
SQL> select sysdate from dual;
30
Output:
SYSDATE
---------
22-JUL-10
Example:
SQL> select hire_date from employee;
Output:HIRE_DATE
---------
21-JUL-10
05-JUN-08
12-FEB-99
Example:
SQL> select add_months(hire_date,3) from employee;
Output:
ADD_MONTH
---------
21-OCT-10
05-SEP-08
12-MAY-99
Example:
SQL> select months_between(sysdate,hire_date) from employee;
Output:
MONTHS_BETWEEN(SYSDATE,HIRE_DATE)
---------------------------------
.047992085
25.5641211
137.338315
Example:
SQL> select next_day(hire_date,'wednesday') from employee;
Output:
NEXT_DAY(
---------
31
28-JUL-10
11-JUN-08
17-FEB-99
Example:
SQL> select last_day(hire_date) from employee;
Output:
LAST_DAY(
---------
31-JUL-10
30-JUN-08
28-FEB-99
Group Functions: - Group functions are built-in SQL functions that operate on groups of rows
and return one value for the entire group. These functions are: COUNT, MAX, MIN, AVG,
SUM, DISTINCT
• Group functions operate on sets of rows to give one result per group of Employees
Dept_id Salary
90 5000
60 5000
Syntax Description
32
A. Select avg(salary), max(salary), min(salary), sum(salary) From employees where job_id like
‘%rep%’;
Groups of Data : Divide rows in a table in to smaller groups by using the group by clause
Employee Table
Dept_id Salary
10 4000
The average
10 5000 salary in
employees
10 6000
table for each
50 5000 department
33
D_id Avg(Salary)
10 5000
50 4000
50 3000
Example:
sql> select first_name from employees union select name from sample ;
Output:
FIRST_NAME
----------
DHANA
GUNA
JAI
JAISANKAR
KUMAR
RAJA
VENKAT
Example:
sql> select first_name from employees union all select name from sample ;
Output:
FIRST_NAME
----------
VENKAT
JAI
DHANA
GUNA
JAISANKAR
VENKAT
RAJA
KUMAR
Example:
sql> select first_name from employees intersect select name from sample ;
Output:
FIRST_NAME
----------
34
VENKAT
Example:
sql> select first_name from employees minus select name from sample ;
Output:
FIRST_NAME
----------
DHANA
GUNA
JAI
JOINS :
A join is the SQL way of combining the data from many tables. It is performed by WHERE
Clause which combines the specified rows of the tables.
Simple join Equi join ( = ) Joins rows using equal value of the
column
Outer join Left outer join ((+) appended to left Rows common in both tables and
operand in join condition) uncommon rows have null value in left
column
Right outer join ((+) appended to
right operand in join condition) Vice versa
35
Simple Join:
a. EQUI JOIN OR INNER JOIN : A column (or multiple columns) in two or more tables
match.
Syntax:
SELECT <column_name(s)>
FROM <table_name1>
INNER JOIN <table_name2>
ON <table_name1.column_name>=<table_name2.column_name>;
Example 1 :
SELECT employee.first_name, department.dname
FROM employee INNER JOIN department
ON employee.deptno = department.deptno;
Output:1
DEPTNO FIRST_NAME
---------- ----------
10 Smith
30 Arun
10 Nithya
Oracle automatically defaults the JOIN to INNER so that the INNER keyword is not required.
They are the same query, though. It is preferred not to type the INNER keyword.
Example 2 using where Condition:
SELECT employee.ename, department.dname
FROM employee JOIN department
ON employee.deptno = department.deptno
WHERE department.dname = 'SALES';
Output 2:
DEPTNO FIRST_NAME
---------- ----------
10 Smith
30 Arun
10 Nithya
36
SELECT <column_name(s)>
FROM <table_name1>
JOIN <table_name2>
ON <table_name1.column_name>=<table_name1.column_name>;
Example1:
SELECT e1.first_name, e2.first_name
FROM employee e1 join employee e2
on e1.mgr = e2.employee_id;
OR
Output:
FIRST_NAME FIRST_NAME
---------------- --------------------
john john
An alias is just a way to refer to a column or table with a UNIQUE name. If we try to call both of
the instances of the table EMP, Oracle wouldn't know which table instance we refer to. Using an
alias clears this confusion
c. OUTER JOIN
An outer join tells Oracle to return the rows on the left or right (of the JOIN clause) even if
there are no rows.
The LEFT OUTER keyword to the JOIN clause says, return the rows to the left (in this case
DEPARTMENT) even if there are no rows on the right (in this case employee).
Syntax:
SELECT <column_name(s)>
37
FROM <table_name1>
LEFT OUTER JOIN <table_name2>
ON <table_name1.column_name>=<table_name2.column_name>;
Example:
SELECT department.dname, employee.first_name
FROM department LEFT OUTER JOIN employee
ON department.deptno = employee.deptno
WHERE department.dname = 'marketing’;
Output:
DNAME FIRST_NAME
-------------- ----------
Marketing
The RIGHT OUTER keyword to the JOIN clause says ,return the rows to the right relation (in
this case DEPARTMENT) even if there are no matching rows on the left relation (in this case
employee).
Syntax:
SELECT <column_name(s)>
FROM <table_name1>
RIGHT OUTER JOIN <table_name2>
ON <table_name1.column_name>=<table_name2.column_name>;
Example:
SELECT employee.first_name, department.dname
FROM employee RIGHT OUTER JOIN department
ON employee.deptno = department.deptno
WHERE department.dname = 'marketing';
Output:
FIRST_NAME DNAME
---------- --------------
marketing
38
FIRST_NAME DNAME
---------- --------------
Nithya accounts
Smith accounts
finance
john IT
Arun IT
marketing
john
e.Cross Join
Displays all the rows and all the colums of both the tables.
Synatx:
SELECT <column_name(s)> FROM <table_name1> CROSS JOIN<table_name2>;
39
Example:
select employee.deptno from employee cross join department;
Or
select employee.deptno from employee,department;
Output:
DEPTNO
----------
10
10
10
10
30
30
30
30
10
10
10
DEPTNO
----------
10
30
30
30
30
f. Natural Join
If two tables have same column name the values of that column will be displayed only once.
Syntax:
SELECT <column_name(s)> FROM <table_name1> Natural JOIN<table_name2>;
Example:
select deptno,first_name from employee natural join department;
Output:
DEPTNO FIRST_NAME
------ ----------
10 Smith
30 Arun
10 Nithya
40
30 john
SUB QUERIES
• Nesting of queries
• A query containing a query in itself A
• Inner most sub query will be executed first
• The result of the main query depends on the values return by sub query
• Sub query should be enclosed in parenthesis
1. Sub query returning only one value
Syntax:
SELECT <column_name(s)> FROM <table_name> WHERE < column name >
< relational op.> < sub query>;
Example:
SELECT employee_id ,first_name FROM employee
WHERE deptno =
(SELECT deptno FROM department
WHERE dname = ‘IT’)
Output:
EMPLOYEE_ID FIRST_NAME
----------- ----------
112 Arun
114 john
Syntax:
SELECT <column_name(s)>
FROM <table_name>
WHERE < column name >
< relational op.> ANY (<sub query>);
Example:
SELECT employee_id ,first_name FROM employee
WHERE salary>= ANY
(SELECT salary FROM employee
WHERE deptno = 30)
AND deptno = 10;
Output:
EMPLOYEE_ID FIRST_NAME
----------- ----------
113 Nithya
112 Arun
111 Smith
114 john
114 john
b. ALL
For the clause all, in contrast, the condition evaluates to true if for all rows selected by the sub
query the comparison holds. In this case the condition evaluates to true if the Sub query does not
yield any row or value.
Syntax:
SELECT <column_name(s)>
FROM <table_name>
WHERE < column name > < relational op.> ALL (<sub query>);
Example:
SELECT employee_id ,first_name FROM employee
WHERE salary > ALL
42
d. NOT IN
Main query displays the values that match with any of the values returned by sub query.
Syntax:
SELECT <column_name(s)>
FROM <table_name>
WHERE < column name > NOT IN (<sub query>);
Example:
43
e. EXISTS
Main query displays the values that match with any of the values returned by sub query.
Syntax:
SELECT <column_name(s)>
FROM <table_name>
WHERE EXISTS (<sub query>);
Example:
SELECT * FROM department
WHERE EXISTS
(SELECT * FROM employee
WHERE deptno = department.deptno);
Output:
DEPTNO DNAME LOC
---------- -------------- -------------
10 accounts chennai
30 IT Bangalore
f. NOT EXISTS
Main query displays the values that match with any of the values returned by sub query.
Syntax:
44
SELECT <column_name(s)>
FROM <table_name>
WHERE NOT EXISTS (<sub query>);
Example:
SELECT * FROM department
WHERE NOT EXISTS
(SELECT * FROM employee
WHERE deptno = department.deptno);
Output:
DEPTNO DNAME LOC
---------- -------------- -------------
20 finance Hyderabad
40 marketing chennai
g. GROUP BY CLAUSE
Often applications require grouping rows that have certain properties and then applying an
aggregate function on one column for each group separately. For this, SQL provides the clause
group by <group column(s)>. This clause appears after the where clause and must refer to
columns of tables listed in the from clause.
Rule:
Select attributes and group by clause attributes should be same.
Syntax:
SELECT <column_name(s)>
FROM <table_name>
Where <conditions>
GROUP BY <column2>, <column1>;
Example:
45
Output:
1. Select all rows that satisfy the condition specified in the where clause.
46
i. ORDER BY
Used along with where clause to display the specified column in ascending order or descending
order . Default is ascending order
Syntax:
SELECT [distinct] <column(s)>
FROM <table>
[ WHERE <condition> ]
[ ORDER BY <column(s) [asc|desc]> ]
Example:
SELECT first_name, deptno, hire_date
FROM employee
ORDER BY deptno ASC, hire_date desc;
Output:
VIEWS
Definition: A view is a named, derived, virtual table. A view takes the output of a query and
treats it as a table; therefore a view can be thought of as a ‘stored query’ or a ‘virtual table’. We
can use views in most places where tables can be used. To the user, accessing a view is like
47
accessing a table. The RDBMS creates an illusion of a table, by assigning a name to the view and
storing its definition in the database.
The tables upon which the views are based are called as ‘base tables’.
CREATION OF A VIEW:
Example:
SQL>create or replace view EMP_VIEW as select * from EMP;
This statement creates a view named EMP_VIEW .The data in this view comes from the
base table EMP. Any changes made to the base table are instantly visible through the view
EMP_VIEW.We can use select statement just like on a table.
SQL>select * from EMP_VIEW;
When create or replace is given, view is created if it is not available otherwise it is recreated.
HOW DOES RDBMS HANDLE THE VIEWS: When a reference is made by a user, the
RDBMS finds the definition of the view stored in the database .It then translates the user’s
request that referenced the view into an equivalent request against the source tables of the view.
Thus RDBMS maintains the illusion of the view.
TYPES OF VIEWS: The different types of views are
• Column subset view
• Row subset view
• Row-Column subset view
• Grouped view
• Joined view
COLUMN SUBSET VIEW:
A column subset view is one where all the rows but only some of the columns of the base
table form the view. The create view
48
Example:
SQL>create or replace view CSV as select empno, ename, sal from EMP;
This view includes only columns empno, ename, sal of EMP table. Since there is no where
clause it includes all the rows.
ROW SUBSET VIEW:
A row subset view is one where all columns but some rows of the source table form the
view. All the columns of the base table participate in the view but all rows do not.
Example:
SQL> create or replace view RSV as select * from EMP where deptno=10;
The where clause restricts the no. of rows to those of employees working in Department Number
10.
ROW-COLUMN SUBSET VIEW:
A row-column subset view is a view which includes only some rows and columns of the
base table.
Example:
SQL>create or replace view RCS as select EMPNO, ENAME, SAL from EMP where
deptno=10;
GROUPED VIEW:
The query specified in the view definition can include the GROUP BY clause. This type
of view is called as Grouped View.
Example:
SQL>create or replace view GV (dno, avgsal) as select deptno, AVG (SAL) from emp group by
deptno;
JOINED VIEWS:
A joined view is formed by specifying a two or more table query in the view definition. A
joined view draws its data from two or more tables and presents the result as a single virtual
table.
Example:
49
Example:
SQL>create or replace force view FVIEW as select * from MYDEPT;
In this query MYDEPT table does not exist, so view is created with compilation errors. When
MYDEPT table is created and this query is executed, the view is automatically recompiled and
become valid.
VIEW WITH CHECK OPTION:
This option specifies that inserts and updates performed through the view must result in
rows that the view query can select. The CHECK OPTION can be used to maintain integrity on a
view.
Example:
SQL>insert into RSV (empno, ename, sal, deptno) values (1000,’dinesh’, 5500, 20);
Though the view is created for deptno 10, we are able to insert records for other department
numbers .This can be restricted using WITH CHECK OPTION clause while creating a view.
Example:
SQL>create view DEPTNO10_VIEW as select * from EMP where deptno=10 WITH CHECK
OPTION CONSTRAINT CHK_DNO10;
The above statement creates a view DEPTNO10 with a check constraint. This will
enforce the view to be inserted or updated only for the department number 10. No other
departments can be inserted or updated.
50
DROPPING A VIEW:
A view can be dropped by using DROP VIEW command.A view becomes invalid if its
associated base table is dropped.
Example:
SQL>drop view DEPTNO10;
This will not affect the base table EMP.
ADVANTAGES OF VIEWS:
• Valid Information: Views let different users see a table from different perspectives. Only
the part that is relevant to the users is visible to them.
• Restricted Access: Views restrict access to the table. Different users are allowed to see
only certain rows or certain columns of a table.
• Simplified Access: Views simplify database access. For example a view that is a join of
three tables where a user does not require all the data in all three tables.
• Data Integrity: Data Integrity can be maintained by having WITH CHECK OPTION
while creating a view.
RESTRICTIONS ON VIEWS:
• A view’s query cannot select the CURRVAL or NEXTVAL pseudo columns.
• If a view’s query selects the ROWID, ROWNUM or LEVEL pseudo columns, they must
have aliases in the view’s query.
• A view can’t be created with an ORDER BY clause.
• A view can’t be updated, deleted and inserted if it is a grouped view.
• A view created from multiple tables can’t be updatable.
• If a view is based on a single underlying table then you can insert, update or delete rows
in this view. This will actually insert, update or delete rows in the underlying table. There
are restrictions again on doing this:
• You cannot insert if the underlying table has a NOT NULL column that does not appear
in the view.
• You cannot insert or update if any of the view’s columns referenced in insert or update
consist of functions or calculations.
51
• You cannot insert, update or delete if the view contains GROUP BY, DISTINCT or a
reference to a pseudo column ROWNUM.
PL/SQL
Overview of PL/SQL
PL/SQL is the procedural extension to SQL with design features of programming languages.
Data manipulation and query statements of SQL are included within procedural units of code.
Pl/SQL Environment
PL/SQL engine
PL/SQL PL/SQL Procedural
P SQL
block block statement
executor
SQL statement executor
The PL/SQL engine in the oracle server process the pl/sql block and it separates SQL staments
and sends them individually to the SQL statements executor
Benefits of PL/SQL
• Integration
• Improved performance
• Modularized program development
• Portability
• Identifiers
52
DECLARE (optional)
BEGIN (Mandatory)
-SQL statements
-PL/SQL statements
EXCEPTION (optional)
END;
DECLARATIVE
It contains all variables, constants, cursors and user defined exceptions that are referenced
in the executable and declarative sections.
EXECUTABLE
It contains SQL statements to manipulate data in the database and PL/SQL statements to
manipulate data in the block.
EXCEPTION HANDLING
It specifies the actions to perform when errors and abnormal conditions arise in the
executable section.
• Anonymous Blocks
53
• Subprograms
Subprograms are named PL/SQL blocks that can accept parameters and can be invoked.
It can be declared either as procedures or as functions.
To write PL/SQL programs, create a script file and run the script file or use editor.
Step1:
Step2:
Step 3:
Step4:
SQL> @z:\oracle\sql\var1.sql
SQL> declare
2 a number:=3;
3 begin
54
4 dbms_output.put_line(a);
5 end;
6 /
3
1 declare
2 v_name varchar2(10);
3 v_regno number;
4 begin
5 v_name:='venkat';
6 v_regno:=39;
9 end;
SQL> /
the no is 39
101 x 102 1
102 y 103 2
103 z 102 3
104 p 102 4
105 q
begin
dbms_output.put_line(v_no);
end;
SQL>/
101
SCALAR VARIABLE
1 declare
56
2 v_name varchar2(10);
3 V_count binary_integer:=10;
4 V_totalsal number(9,2);
5 v_orderdate date:=sysdate;
9 begin
10 v_name:='venkat';
11 v_totalsal:=10000.23;
12 dbms_output.put_line(v_name);
13 dbms_output.put_line(v_count);
14 dbms_output.put_line(v_orderdate);
15 dbms_output.put_line(c_tax);
16 dbms_output.put_line(v_regno);
17 end;
18 /
venkat
10
19-AUG-05
6.23
23
1 declare
2 v_no emp.ssn%type;
3 V_name varchar2(10):='venkat';
4 name v_name%type;
5 begin
6 v_no:=10;
7 name:='ven';
8 dbms_output.put_line(v_no);
9 dbms_output.put_line(name);
10*end;
11 /
10
ven
BIND VARIABLES
A bind variable is a variable that is declared in a host environment. Bind variables can be
used to pass run-time values, which can be either number or character, into or out of one or more
PL/SQL programs.
58
Example:
SQL> ed
File:
1 begin
3 dbms_output.put_line(:a);
4 end;
SQL> /
101
SQL> print a;
----------
101
To reference host variables, prefix the references with a colon (:) to distinguish them
from declared PL/SQL variable.
59
SQL> declare
2 v_sal number(9,2):=&aa;
3 begin
4 :gg:=v_sal/12;
5 end;
6 /
GG
----------
83.3333333
• Delimiters
• Identifiers, which include reserved words
• Literals
• Character literals
• Numeric literals
COMMENTS:
/* beginning */ ending
60
• SQLCODE
• SQL ERRM
SQL> ed
1 declare
2 vdate date;
3 begin
5 dbms_output.put_line(vdate);
6 end;
SQL> /
19-AUG-05
All SQL functions are allowed except decode function and group functions.
SQL> declare
2 v_a number:=3;
3 begin
4 declare
5 v_b number:=4;
6 begin
7 dbms_output.put_line(v_b);
dbms_output.put_line(v_a);
8 end;
9 dbms_output.put_line(v_a);
10 end;
11 /
SQL> ed
62
1 <<outer>>
2 declare
3 v_a number:=3;
4 begin
5 declare
6 v_a number:=4;
7 begin
8 dbms_output.put_line(v_a);
9 dbms_output.put_line(outer.v_a);
10 end;
11 end;
12 /
PROGRAMMING GUIDELINES:
63
NOTES:
101 x 102 1
102 y 103 2
103 z 102 3
104 p 102 4
105 q
SQL> ed
1 declare
2 v_ssn number;
64
3 v_name varchar2(10);
4 begin
6 dbms_output.put_line(v_ssn);
7 dbms_output.put_line(v_name);
8 end;
SQL> /
101
a 3000 4000
b 5000 6000
c 3000 6000
d 4000 10000
e 2000 6000
SQL> ed
1 declare
65
2 v_lsal job_grade.lowest_sal%type;
3 v_hsal job_grade.highest_sal%type;
4 begin
6 dbms_output.put_line(v_lsal);
7 dbms_output.put_line(v_hsal);
8 end;
9 /
17000
32000
NAMING CONVENTIONS
A local variable in pl/sql name must not be equal to column names present in database .
declare
lastname varchar2(10);
begin
The above code will delete all employees because of the naming convention problem.
SUBSTIUTION VARIABLE:
SQL> ed
1 declare
2 v_sal number;
3 begin
4 v_sal:=&v_sal;
5 dbms_output.put_line(v_sal);
6 end;
7 /
2000
INSERTION
SQL> ed
1 begin
3 dbms_output.put_line('record inserted');
4 end;
5 /
record inserted
67
SQL> ed
1 begin
3 dbms_output.put_line('record inserted');
4 end;
SQL> /
record inserted
UPDATE:
SQL> ed
1 declare
2 v_sal number;
3 begin
4 v_sal:=&v_sal;
6 dbms_output.put_line('record updated');
68
7 end;
SQL> /
record updated
a 12000 4000
b 5000 6000
c 3000 6000
d 4000 10000
e 2000 6000
DELETE:
SQL> ed
1 declare
2 v_sal number;
3 begin
4 v_sal:=&v_sal;
6 dbms_output.put_line('record deleted');
7 end;
69
8 /
record deleted
a 12000 4000
c 3000 6000
d 4000 10000
e 2000 6000
CONTROL STRUCTURES
• IF statements
If –then-end if
If-then-else-end if
If-then-elseif-end if
• Case expressions
• Loop statements
Basic loops
While loops
For loops
70
Syntax of IF:
If condition then
Statements;
Statements;
Else
Statements;
End if;
Examples:
1 declare
2 a number;
3 b number;
4 begin
5 a:=&a;
6 b:=&b;
7 if a>b then
9 else
11 end if;
12 end;
71
SQL> /
new 6: b:=4;
greatest number is12
20 it 300 1800
1 declare
2 v_id departments.dept_id%type;
3 v_dname departments.dept_name%type;
4 begin
72
6 if v_id=11 then
7 dbms_output.put_line(v_dname);
9 dbms_output.put_line(v_id);
10 else
12 end if;
13 end;
SQL> / 10
1 declare
2 a number;
3 b number;
4 c number;
5 begin
6 a:=&a;
7 b:=&b;
8 c:=&c;
73
13 else
14 dbms_output.put_line('greatest number is'||c);
15 end if;
16 end;
SQL>/
C is greater :12.
4) Case Expressions
A case expression selects a result and returns it. To select the result, the case expression
uses an expression whose value is used to select one of several alternatives.
Syntax :
CASE selector
WHEN
expression1
THEN result1 WHEN
expression2
THEN result2
---------
74
Example:
1 declare
2 va varchar2(10);
3 v_result varchar2(10);
4 begin
5 va:=&va;
6 v_result:=
7 CASE va
8 WHEN 'a' THEN 'excellent'
9 WHEN 'b' THEN 'very good'
10 WHEN 'c' THEN 'good'
11 ELSE 'poor'
12 end;
13 dbms_output.put_line('grade is'||v_result);
14 end;
15 /
new 5: va:='a';
grade is excellent
SQL> /
new 5: va:='b';
grade is very good
SQL> /
new 5: va:='c';
grade is good
5) General Loop
Syntax:
LOOP
...
IF ... THEN
...
EXIT; -- exit loop immediately
END IF;
END LOOP;
76
6) While Loop
Syntax:
Example:
declare
var number:=1;
Begin
While var<10 Loop
dbms_output.put_line(‘var= ‘ ||var);
var:=var+1;
End Loop;
End;
77
7) For Loop
Syntax:
FOR counter IN [REVERSE] lower_bound..upper_bound LOOP
sequence_of_statements;
...
END LOOP;
Example:
Declare
Var number;
Begin
For var in 1..10
loop
Dbms_output.put_line(var);
End loop;
End;
8) Goto Syntax:
Syntax:
If <cond> Then
GOTO <lbl1>
End if;
CURSORS
The oracle server uses work areas, called private SQL areas, to execute SQL statement and to
store processing information. This area is called cursor.
78
Cursor types:
Explicit cursor
Fetch
Syntax:
Cursor declaration
Fetch
79
Explicit Cursor Attributes: To determine the status of the cursor, the cursor’s attributes are
checked.Cursors have the following four attributes that can be used in a PL/SQL program.
%isopen -To check if the cursor is opened or not
%found-To check if a record is found and can be fetched from the cursor
%rowcount-To check for the number of rows fetched from the cursor
%isopen, %found,%notfound are boolean attributes which are set to either TRUE or
FALSE.
A Simple Example:
1 declare
2 v_name wer1.name%type;
3 v_ssn wer1.ssn%type;
5 begin
6 open emp_c;
9 dbms_output.put_line(v_name);
10 end loop;
11 close emp_c;
12 end;
SQL> / x
x
x
y
y
2) %row count
1 declare
2 v_name wer1.name%type;
3 v_ssn wer1.ssn%type;
5 begin
6 open emp_c;
10 dbms_output.put_line(v_name);
11end loop;
12 close emp_c;
13 end;
SQL> / x
x
81
It processes the rows of the active set by fetching values into a PL/SQL record.
1 declare
2 cursor emp_c is select * from wer1;
3 emp_record emp_c%rowtype;
4 begin
5 open emp_c;
6 for i in 1..5 loop
7 fetch emp_c into emp_record;
8 exit when emp_c%notfound;
9 insert into wer(name,ssn) values(emp_record.name,emp_re
10 end loop;
11 commit;
12 close emp_c;
13 end;
14 /
PL/SQL procedure successfully completed.
NAME SSN
---------- ----------
x 101
82
x 101
x 101
x 101
x 101
x 101
x 101
x 101
x 101
x 101
y 102
y 102
12 rows selected.
It passes the parameter values to the cursor in a cursor FOR loop. This means that you can
open and close an explicit cursor several times in a block, returning a different active set on
each occasion.
Example:
1 declare
2 v_number number;
3 v_name varchar2(10);
6 begin
7 open c1(101,'x');
83
9 dbms_output.put_line(v_number);
10 close c1;
11 open c1(102,'y');
13 dbms_output.put_line(v_number);
14 close c1;
15 end;
16 /
101
102
5) Update
The update clause in the cursor query locks the affected rows when the cursor is opened.
Example:
declare
v_number number;
v_name varchar2(10);
cursor c1(eno number,ename varchar2) is select ssn,name from emp where ssn=eno and
begin
84
open c1(101,'x');
dbms_output.put_line(v_number);
close c1;
open c1(102,'y');
fetch c1 into v_number,v_name;
dbms_output.put_line(v_number);
close c1;
end;
EXCEPTIONS
Syntax
When exception1
then Statement1
Statement2
……..
When exception2
then Statement1
Statement2
……..
When others
then Statement1
85
Statement2 ……..
NO_DATA_FOUND
TOO_MANY_ROWS
INVALID_CURSOR
ZERO_DIVIDE
DUP_VAL_ON_INDEX
Example:
1)
1 declare
2 a number;
3 b number;
4 c number;
5 begin
6 a:=5;
7 b:=0;
8 c:= a/b;
9 exception
12 end;
86
SQL> /
2) Non-predefined error
1. Declare the name for the exception within the declarative section
2. Associate the declared exception with the standard oracle server error number using the
PRAGMA EXCEPTION_INIT statement
Syntax : PRAGMA EXCEPTION_INIT(exception, error_number);
3. Reference the declared exception within the corresponding exception –handling routine.
Example:
1 declare
2 emp_remain exception;
3 pragma exception_init
4 (emp_remain,-2292);
5 begin
7 commit;
8 exception
11end;
87
SQL> /
SQL> /
When an exception occurs, you can identify the associated error code or error message by
using two functions.
SQLERRM: It returns character data containing the message associated with the error
number.
Syntax:
declare;
v_error_code number;
v_error_messgage varchar2(255);
88
begin
when others then rollback;
v_error_code:=sqlcode;
v_error_message:=sqlerrm;
dbms_output.put_line(v_error_code||v_error_message);
end;
Example:
1 declare
2 invalid_dept exception;
3 begin
5 if sql%notfound then
6 raise invalid_dept;
7 end if;
8 exception
11 end;
89
• Anonymous Blocks
It is unnamed blocks. It is declared at the point in an application where they are to be
executed and are passed to the PL/SQL engine for execution at run time.
• Subprograms
Subprograms are named PL/SQL blocks that can accept parameters and can be invoked.
It can be declared either as procedures or as functions.
Overview of subprograms
A subprogram is named PL/SQL block that ca accept parameters and be invoked from a calling
environment.
Benefits of subprograms
• Easy maintenance
• Improved data security and integrity
90
• Improved performance
• Improved code clarity
Procedure
A procedure is a type of subprogram that performs an action. A procedure can be stored in the
database, as a schema object, for repeated execution.
Is| As
PL/SQL Block;
The replace option indicates that if the procedure exists, It will be dropped and replaced with the
new version created by the statement. Parameter name of a PL/SQL variable whose value is
passed to or populated by the calling environment.
IN, OUT, IN OUT
IN parameter
IN parameters are passed as constants from the calling environment into the procedure.
91
Example:1
2 (grade in job_grade.gra%type)
3 is
4 begin
6* end raise_salary;
7 /
Procedure created.
c 3000 6000
d 4000 10000
e 2000 6000
92
Example:1
2 (g in job_grade.gra%type,
5 is
6 begin
8* end info;
9 /
SQL> @g:\oracle\sql\info1
Procedure created.
1.Run the sql script file to generate and compile the source code.
3.Invoke the procedure, supplying these host variables as the OUT parameters.: reference the
93
4.To view the values passed from the procedure to the calling environment ,use the print
command.
G_SAL
----------
13200
G1_SAL
----------
4000
IN OUT parameter
Example:1
2 (g in out number)
3 is
4 begin
6* end info;
7 /
94
Procedure created.
1 begin
2 :g_sal:=4000;
3* end;
G_SAL
----------
4000
G_SAL
----------
13200
Named : List actual parameters in library order by associating each with its
Combination : List some of the actual parameters as positional and some as named.
95
Removing procedures
Syntax:
Example:
Functions
A function is a named PL/SQL block that returns a value. A function can be stored in the
database as a schema object for repeated execution. A function is called as part of an expression.
Syntax:
….)]
Return datatype
Is/as
PL/SQL block ;
96
Example:
declare
summation number;
average number;
begin
return(m4+m5);
end;
begin
return(summ1/2);
end;
begin
summation:=summa(&m1,&m2);
average:=aver(summation);
dbms_output.put_line('summation is:'||summation);
dbms_output.put_line('average is:'||average);
end;
Removing functions
97
Example:
Packages
Packages bundle are related PL/SQL types, items, and subprograms into one container.
A package usually has a specification and a body, stored separately in the database.
Package specification
It is the interface to the application. It declares the types, variables, constants, exceptions,
cursors and subprograms.
A package specification can exist without a package body, but a package body cannot exist
without a package specification.
Syntax
is| as
Subprograms specifications
End package_name;
Example:
2 g_comm number:=0.10;
3 procedure reset_comm
4 (p_comm in number);
98
5 end commp;
Package created.
Package body
Syntax
Is| as
Subprogram bodies
End package_name;
Example
2 is
4 return boolean
5 is
6 v_max_comm number;
7 begin
10 else return(true);
99
11 end if;
12 end validate_comm;
14 is
15 begin
16 if validate_comm(p_comm)
17 then g_comm:=p_comm;
18 else
19 raise_application_error(-20210,'invalid commision');
20 end if;
21 end reset_comm;
22 end commp;
23 /
2 a constant number:=2;
4 end global_con;
5 /
Package created.
100
20 miles=40km
2 is
3 begin
4 y :=x *global_con.a;
5 end me;
SQL> /
Procedure created.
YA
----------
Removing packages:
101
Overloading
It is the use of same name for different subprograms inside a PL/SQL block, a subprogram, or a
package.
Example:
2 is
5 end over;
6 /
Package created
3 is
4 begin
6 end add_dept;
8 is
9 begin
11 end add_dept;
102
12 end overp;
Trigger
A trigger is aPL/SQL block or a PL/SQL procedure associated with a table ,view, schema, or the
database. It executes implicitly whenever a particular event takes place.
It can be:
Database trigger: fires whenever a data event or system event occurs on a schema or database.
• Triggering timing
o For table: BEFORE, AFTER
o For view: INSTEAD OF
• Triggering event: INSERT, UPDATE, or DELETE
• Table name: on table, view
• Trigger type: row or statement
• When clause: restricting condition
• Trigger body: PL/SQL block
Trigger type
Statement trigger:The trigger body executes once for the triggering event. this is default. A
statement trigger fires once, even if no rows are affected at all.
Row trigger:The trigger body executes once for each row affected by the triggering event. A
row trigger is not executed if the triggering event affects no rows.
Syntax:
103
Timing
ON table_name
Trigger _body
Example:
create trigger ab
begin
raise_application_error(-20000,'not accessible')
end
This program raises an error during insertion and deletion and update operation in a row.
_____________________________________________________________________
104