SQL
SQL
opasdfghjklzxcvbnmqwertyuiopasdfgh
jklzxcvbnmqwertyuiopasdfghjklzxcvb
nmqwertyuiopasdfghjklzxcvbnmqwer
tyuiopasdfghjklzxcvbnmqwertyuiopas
ReferenceManual
dfghjklzxcvbnmqwertyuiopasdfghjklzx
cvbnmqwertyuiopasdfghjklzxcvbnmq
for
wertyuiopasdfghjklzxcvbnmqwertyuio
DatabaseSystemsLab
pasdfghjklzxcvbnmqwertyuiopasdfghjk
lzxcvbnmqwertyuiopasdfghjklzxcvbnm
qwertyuiopasdfghjklzxcvbnmqwertyuio
pasdfghjklzxcvbnmqwertyuiopasdfghj
klzxcvbnmqwertyuiopasdfghjklzxcvbn
Vellore632014,TamilNadu
mqwertyuiopasdfghjklzxcvbnmrtyuio
pasdfghjklzxcvbnmqwertyuiopasdfghj
klzxcvbnmqwertyuiopasdfghjklzxcvbn
Faculty Associated :
Prof. M.Venkatesan, A.P(SG)
Prof. Hari Seetha, A.P(SG)
Prof. K.Govinda, A.P(SG)
Prof. E.Anupriya, A.P(SG)
Prof. L.Ramanathan,
A.P
Prof. M.Anbarasi,
A.P
Prof. J.N.Swathi,
A.P
Prof. A.Geetha Mary,
A.P
Prof. K.Sharmila Bhanu, A.P
Prof. S.Arun Kumar,
A.P
Prof. G.Guru Raghav, A.P
CONTENTS
SNo
Topics
Page Number
1.
2.
CONSTRAINTS
15
3.
OPERATORS IN SQL*PLUS
23
4.
25
5.
JOINS
35
6.
VIEWS
47
7.
PL/SQL
52
8.
52
70
10
CURSORS
78
11
EXCEPTIONS
85
12
90
13
PACKAGES
98
14
TRIGGERS
103
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 users 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
-------------------------EMPLOYEE_ID
FIRST_NAME
LAST_NAME
MGR
HIRE_DATE
JOB_ID
SALARY
COMMISION
DEPTNO
Type
---------------------NUMBER(3)
VARCHAR2(10)
VARCHAR2(10)
NUMBER(4)
DATE
VARCHAR2(10)
NUMBER(10)
NUMBER(8)
NUMBER(2)
4
DEPARTMENT
Name
--------------DEPTNO
DNAME
LOC
Type
----------------NUMBER(2)
VARCHAR2(14)
VARCHAR2(13)
BONUS
Name
---------------ENAME
JOB
SAL
COMM
Type
------------------VARCHAR2(10)
VARCHAR2(9)
NUMBER(10,2)
NUMBER(10)
JOBGRADE
Name
----------------JOB_ID
GRADE
LOSAL
HISAL
Type
--------------------VARCHAR2(10)
NUMBER
NUMBER
NUMBER
Description
VARCHAR2(size)
CHAR(size)
NUMBER(p,s)
DATE
LONG
CLOB
BLOB
BFILE
ROWID
No need to specify the size of table, the size is ultimately defined by the amount of space
allocated to the database as a whole.
NAMING RULES
Table names and Column names
Must not duplicate the name of another object owned by the same user
( 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:
SQL> create table department
(deptno number(2),
dname varchar(14),
loc varchar(13));
Output:
Table created.
Note:
Other tables can be created in the similar way.
b. To view the Structure of the table, desc command is used
SQL> desc employee;
Name
Null?
Type
-------------------------------------- -------- --------------EMPLOYEE_ID
NUMBER(3)
7
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)
Decrease the width of the column only if the column contains only null values or if the table
has no rows
Change the data type only if the column contains null values
8
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.
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
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
Using Alias name for a field
Syntax:
Select <col1> <alias name 1> , <col2> < alias name 2> from < tab1>;
Example:
SQL> select dname, loc as location from department;
Output:
DNAME
LOCATION
-------------- ------------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
Creating Table using subquery
Syntax:
Create table <new _table_name> as Select <column names> from <old_table_name>;
Example:
SQL> create table copyOfEmp as select * from employee;
Output:
Table created.
Smith
0.1
10
DEPTNO
Ford
222
21-JUL-10
J1
30000
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.
Inserting into table using a subquery
Syntax :
Insert into <new_table_name> (Select <columnnames> from <old_table_name>);
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
NOT NULL
UNIQUE
PRIMARY KEY
FOREIGN KEY
CHECK
first_name
last_name
VARCHAR2(25) UNIQUE,
VARCHAR2(10),
salary
NUMBER(8,2) CHECK(SALARY>0),
deptid NUMBER(4)
);
2. Creating constraints with constraint name
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
first_name
VARCHAR2(20),
last_name
phone_number VARCHAR2(20),
job_id
salary
CONSTRAINT
);
3. With check constraint
Syntax:
CREATE TABLE < tablename> (
<column name1 >
< datatype> ,
< datatype>,
Example:
CREATE TABLE emp_demo4
( emp_id
NUMBER(6),
emp_name VARCHAR2(15),
salary
);
Adding Constriants
Constraints can be added after the table creation by using alter command
Operators in SQL*PLUS
Type
Symbol / Keyword
Where to use
Arithmetic
+,-,*,/
Comparison
Logical
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.
Search conditions can contain either characters or numbers
%
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
Note: Inserting null value into location column of department table
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
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
Comparison operators
NOT operator
AND operator
OR operator----Lowest precedence
23
Output:
FIRST_NAME
DEPTNO
SALARY
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
---------- ---------- ---------Smith
10
30000
SALARY
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
---------10
30
40
DNAME
LOC
-------------- ------------accounts
chennai
IT
Bangalore
marketing
chennai
FUNCTIONS
Group functions
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
initcap (char)
lower (char)
upper (char)
substr(char, m , n)
chr(number)
length(char)
Length of string
Examples:
Function
Input
Output
Initcap(char)
Hello
Lower(char)
fun
Upper(char)
SUN
Ltrim(char, set)
hello
Rtrim(char, set)
xyzhe
translate(char,from,to)
back
Replace(char,from,to)
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**********
Length: returns the length of a string
Example:
SQL> select dname, length(dname) from department;
Output:
DNAME
LENGTH(DNAME)
-------------- ------------accounts
8
finance
7
IT
2
marketing
9
Sales
5
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
abs ( )
ceil ( )
cos ( )
exp ( )
Exponent value
floor( )
Truncated value
power (m,n)
N raised to m
mod
Remainder of m / n
(m,n)
round (m,n)
trunc (m,n)
sqrt
(m)
Examples:
Function
Input
Output
Abs( n)
15
28
Ceil(n)
49
Cos(n)
Cosh(n):
-0.59884601
1
Exp(n)
54.59815
Floor(n)
Power(m ,n)
25
Mod(m ,n)
Round(m ,n)
112.26
Example:
SQL> select ln (2) from dual; (returns natural logarithm value of 2)
SQL>select sign (-35) from dual; (output is -1)
CONVERSION FUNCTIONS: Convert a value from one data type to another.
To_char ( )
To_ char (d [,fmt]) where d is the date fmt is the format model which specifies the format of the
date. This function converts date to a value of varchar2datatype in a form specified by date
format fmt.if fmt is neglected then it converts date to varchar2 in the default date format.
Example:
SQL> select to_char (hire_date, 'ddth "of" fmmonth yyyy') from employee;
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
Return Value
ADD_MONTHS (date, n)
LAST_DAY (x)
SYSDATE
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
90
10000
90
10000
60
5000
60
5000
The maximum
salary in the
employees table
Description
count (*),
Max(salary)10000
table
[where
condition]
[GROUP BY column];
Example:
Q.Display the average,highest, lowest and sum of salaries for all the sales representatives.
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
10
5000
10
6000
50
5000
Theaverage
salaryin
employees
tableforeach
department
33
50
D_id
Avg(Salary)
10
5000
50
4000
3000
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.
Type
Simple join
Sub type
Description
Equi join ( = )
Non equi join (<, <=, >, >=, !=, < >
)
Self join
Outer join
35
Vice versa
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
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
-------------Marketing
FIRST_NAME
----------
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
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
30
10
---------Smith
Arun
Nithya
40
30
john
SUB QUERIES
Nesting of queries
The result of the main query depends on the values return by sub query
Output:
EMPLOYEE_ID FIRST_NAME
-------------------112
Arun
114
john
2. Sub query returning more than one value
a. ANY
For the clause any, the condition evaluates to true if there exists at least one row selected by the
sub query for which the comparison holds. If the sub query yields an empty result set, the
condition is not satisfied.
41
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
112
111
114
114
---------Nithya
Arun
Smith
john
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
----------
113
Nithya
c. 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 > IN (<sub query>);
Example:
SELECT employee_id ,first_name FROM employee
WHERE deptno IN
(SELECT deptno FROM department
WHERE loc = Bangalore);
Output:
EMPLOYEE_ID FIRST_NAME
-----------
----------
114
john
112
Arun
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
LOC
accounts
30
IT
chennai
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
finance
40
marketing
Hyderabad
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
----------13000
----------40000
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:
FIRST_NAME
---------Smith
Nithya
john
Arun
john
DEPTNO HIRE_DATE
-----------------10
21-JUL-10
10
12-FEB-99
30
20-JAN-10
30
05-JUN-08
20-JAN-10
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:
The syntax for creating a view is given by:
create [or replace][[no][force]]view <view_name>
<query>[with[check option]read only][constraint]];
[column
alias
name]as
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 users
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
SQL>create
or
replace
view
JV(empno,ename,sal,dname,loc)
as
select
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:
If a views query selects the ROWID, ROWNUM or LEVEL pseudo columns, they must
have aliases in the views query.
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 views 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/SQLengine
PL/SQL
block
PL/SQL
PSQL
block
Procedural
statement
executor
SQLstatementexecutor
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
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.
4 dbms_output.put_line(a);
5 end;
6 /
3
SQL> /
the name is venkat
the no is 39
NAME
ESSN
DEPTNO
SALARY
102
102
103
103
102
104
102
105
SCALAR VARIABLE
It holds a single value and has no internal components.
Examples : number, character, date, boolean
2 v_name varchar2(10);
3 V_count binary_integer:=10;
4 V_totalsal number(9,2);
5 v_orderdate date:=sysdate;
6 c_tax constant number(3,2):=6.23;
7 v_valid boolean not null:=true;
8 v_regno number default 23;
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
DECLARING VARIABLE WITH THE %TYPE ATTRIBUTE
The % type attribute is used to declare a variable according to:
57
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> variable a number;
SQL> ed
File:
1 begin
2 select ssn into:a from emp where name='x';
3 dbms_output.put_line(:a);
4 end;
SQL> /
101
PL/SQL procedure successfully completed.
SQL> print a;
A
---------101
60
SQLCODE
SQL ERRM
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 /
4
3
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 /
4
3
PL/SQL procedure successfully completed.
PROGRAMMING GUIDELINES:
Category
Case Conversion
Examples
SQL statements
uppercase
SELECT,INSERT
PL/SQL statements
uppercase
DECLARE,BEGIN,IF
63
Data types
uppercase
VARCHAR2,BOOLEAN
Identifiers
lowercase
v_sal
lowercase
emp, dept
NOTES:
NAME
ESSN
DEPTNO
SALARY
102
102
103
103
102
104
102
105
SQL> ed
1 declare
2 v_ssn number;
64
3 v_name varchar2(10);
4 begin
5 select ssn,name into v_ssn,v_name from emp where name='x';
6 dbms_output.put_line(v_ssn);
7 dbms_output.put_line(v_name);
8 end;
SQL> /
101
x
PL/SQL procedure successfully completed.
LOWEST_SAL
HIGHEST_SAL
3000
4000
5000
6000
3000
6000
4000
10000
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
5 select sum(lowest_sal),sum(highest_sal) into v_lsal,v_hsal from job_grade;
6 dbms_output.put_line(v_lsal);
7 dbms_output.put_line(v_hsal);
8 end;
9 /
17000
32000
PL/SQL procedure successfully completed.
NAMING CONVENTIONS
A local variable in pl/sql name must not be equal to column names present in database .
declare
lastname varchar2(10);
begin
delete from emp where lastname-lastname;
The above code will delete all employees because of the naming convention problem.
1 declare
2 v_sal number;
3 begin
4 v_sal:=&v_sal;
5 dbms_output.put_line(v_sal);
6 end;
7 /
Enter value for v_sal: 2000
2000
PL/SQL procedure successfully completed.
INSERTION
SQL> ed
Wrote file afiedt.buf
1 begin
2 insert into emp(ssn,name) values(123,'venkat');
3 dbms_output.put_line('record inserted');
4 end;
5 /
record inserted
PL/SQL procedure successfully completed.
67
UPDATE:
SQL> ed
Wrote file afiedt.buf
1 declare
2 v_sal number;
3 begin
4 v_sal:=&v_sal;
5 update job_grade set lowest_sal=v_sal where gra='a';
6 dbms_output.put_line('record updated');
68
7 end;
SQL> /
Enter value for v_sal: 12000
record updated
PL/SQL procedure successfully completed.
SQL> select *from job_grade;
GRA LOWEST_SAL
HIGHEST_SAL
12000
4000
5000
6000
3000
6000
4000
10000
2000
6000
DELETE:
SQL> ed
Wrote file afiedt.buf
1 declare
2
v_sal number;
begin
4 v_sal:=&v_sal;
5
6 dbms_output.put_line('record deleted');
7 end;
69
8 /
Enter value for v_sal: 5000
record deleted
12000
4000
3000
6000
4000
10000
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;
Else if condition then
Statements;
Else
Statements;
End if;
Examples:
1) Find the greatest among two numbers
1 declare
2 a number;
3 b number;
4 begin
5 a:=&a;
6 b:=&b;
7 if a>b then
8 dbms_output.put_line('gratest number is'||a);
9 else
10 dbms_output.put_line('gratest number is'||b);
11 end if;
12 end;
71
SQL> /
Enter value for a: 12 old 5: a:=&a;
new 5: a:=12;
Enter value for b: 4 old 6: b:=&b;
new 6: b:=4;
greatest number is12
PL/SQL procedure successfully completed
DEPT_NAME
MANAGER_ID
LOCATION_ID
---------
----------
----------
-----------
10
cse
200
1700
20
it
300
1800
30
mech
400
1500
40
ece
500
1600
1 declare
2 v_id departments.dept_id%type;
3 v_dname departments.dept_name%type;
4 begin
72
1 declare
2 a number;
3 b number;
4 c number;
5 begin
6 a:=&a;
7 b:=&b;
8 c:=&c;
9 if (a>b) and (a>c) then
10 dbms_output.put_line('gratest number is'||a);
73
Syntax :
CASE selector
WHEN
expression1
THEN result1 WHEN
expression2
THEN result2
--------WHEN expression N THEN result
N [ELSE resultN+1
END;
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 /
SQL> Enter value for va: 'a' old 5: va:=&va;
new 5: va:='a';
grade is excellent
PL/SQL procedure successfully completed.
SQL> /
Enter value for va: 'b' old 5: va:=&va;
new 5: va:='b';
grade is very good
PL/SQL procedure successfully completed.
SQL> /
Enter value for va: 'c' old 5: va:=&va;
75
new 5: va:='c';
grade is good
PL/SQL procedure successfully completed.
5) General Loop
Syntax:
LOOP
...
IF ... THEN
...
EXIT; -- exit loop immediately
END IF;
END LOOP;
6) While Loop
Syntax:
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
Active set: set of rows returned by multiple rows
Syntax:
Cursor declaration
cursor cuname is select;
Open the cursor
open cursor name;
Close the cursor
close cursor name;
Fetch
fetch cname into variable or record
79
Explicit Cursor Attributes: To determine the status of the cursor, the cursors 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
%notfound-To check if no more records can be 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;
4 cursor emp_c is select * from wer1;
5 begin
6 open emp_c;
7 for i in 1..5 loop
8 fetch emp_c into v_name,v_ssn;
9 dbms_output.put_line(v_name);
10 end loop;
11 close emp_c;
12 end;
2) %row count
1 declare
2 v_name wer1.name%type;
3 v_ssn wer1.ssn%type;
4 cursor emp_c is select * from wer1;
5 begin
6 open emp_c;
7 for i in 1..5 loop
8 fetch emp_c into v_name,v_ssn;
9 exit when emp_c%rowcount>4;
10 dbms_output.put_line(v_name);
11end loop;
12 close emp_c;
13 end;
SQL> / x
x
x
81
y
PL/SQL procedure successfully completed.
NAME
SSN
----------
----------
101
82
101
101
101
101
101
101
101
101
101
102
102
12 rows selected.
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
name=ename for update of name nowait;
begin
84
open c1(101,'x');
fetch c1 into v_number,v_name;
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
10 when zero_divide then
11 dbms_output.put_line('zero divide error');
12 end;
86
SQL> /
zero divide error
PL/SQL procedure successfully completed.
2) Non-predefined error
Example:
1 declare
2 emp_remain exception;
3 pragma exception_init
4 (emp_remain,-2292);
5 begin
6 delete from emp where deptno=&deptno;
7 commit;
8 exception
9 when emp_remain then
10 dbms_output.put_line('cannot remove dept'|| 'employee exist');
11end;
87
SQL> /
Enter value for deptno: 2
old 6: delete from emp where deptno=&deptno;
new 6: delete from emp where deptno=2;
cannot remove deptemployee exist
PL/SQL procedure successfully completed
SQL> /
Enter value for deptno: 8
old 6: delete from emp where deptno=&deptno;
new 6: delete from emp where deptno=8;
PL/SQL procedure successfully completed
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
4 delete from emp where deptno=&deptno;
5 if sql%notfound then
6 raise invalid_dept;
7 end if;
8 exception
9 when invalid_dept then
10 dbms_output.put_line('the deptnumber is not valid');
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.
Two types of subprograms
Benefits of subprograms
Easy maintenance
Improved performance
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.
Syntax for creating procedure:
Create [or replace] procedure <procedure_name>
[( parameter1 [mode1] datatype1,parameter2 [mode2] datatype2,..)]
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.
Mode: type of argument
IN,OUT,IN OUT
IN
IN parameter
IN parameters are passed as constants from the calling environment into the procedure.
91
Example:1
1 create or replace procedure raise_salary
2 (grade in job_grade.gra%type)
3 is
4 begin
5 update job_grade set lowest_sal=lowest_sal*1.10 where gra= grade;
6* end raise_salary;
7 /
Procedure created.
SQL> execute raise_salary('a'); // executing procedure
PL/SQL procedure successfully completed.
SQL> select * from job_grade;
LOWEST_SAL
GRA
HIGHEST_SAL
13200
3000
4000
2000
4000
6000
10000
6000
92
Example:1
1 create or replace procedure info
2 (g in job_grade.gra%type,
3 l_sal out job_grade.lowest_sal%type,
4 h_sal out job_grade.highest_sal%type)
5 is
6 begin
7 select lowest_sal,highest_sal into l_sal,h_sal from job_grade where gra=g;
8* end info;
9 /
SQL> edit g:\oracle\sql\info1.sql
SQL> @g:\oracle\sql\info1
Procedure created.
Procedure created.
SQL> variable g_sal number;
1 begin
2 :g_sal:=4000;
3* end;
PL/SQL procedure successfully completed.
Named
Combination : List some of the actual parameters as positional and some as named.
95
Removing procedures
Drop a procedure stored in the database
Syntax:
Drop procedure procedure_name
Example:
Drop procedure raise_salary;
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:
Create [or replace] function function_name
[(parameter1 [mode1] datatype1,
Parameter2 [mode2] datatype2,
.)]
Return datatype
Is/as
PL/SQL block ;
96
Example:
declare
summation number;
average number;
function summa(m4 number,m5 number) return number is
begin
return(m4+m5);
end;
function aver( summ1 number) return number is
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
Drop function function_name
97
Example:
Drop function summa;
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
Create [or replace] package package_name
is| as
Public type and item declarations
Subprograms specifications
End package_name;
Example:
1 create or replace package commp is
2 g_comm number:=0.10;
3 procedure reset_comm
4 (p_comm in number);
98
5 end commp;
Package created.
Package body
Syntax
Create [or replace] package body package_name
Is| as
Private type and item declarations
Subprogram bodies
End package_name;
Example
1 create or replace package body commp
2 is
3 function validate_comm(p_comm in number)
4 return boolean
5 is
6 v_max_comm number;
7 begin
8 select max(lowest_sal) into v_max_comm from job_grade;
9 if p_comm>v_max_comm then return(false);
10 else return(true);
99
11 end if;
12 end validate_comm;
13 procedure reset_comm(p_comm in number)
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 /
Package body created.
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:
1 create or replace package over
2 is
3 procedure add_dept(p_n in emp.ssn%type,p_na in emp.name%type);
4 procedure add_dept(p_n in emp.ssn%type,p_na in emp.name%type,p_dept in
emp.deptno%type);
5 end over;
6 /
Package created
1 create package body overp is
2 procedure add_dept(p_n emp.ssn%type,p_na emp.name%type)
3 is
4 begin
5 insert into emp (ssn,name) values(p_n,p_na);
6 end add_dept;
7 procedure add_dept(p_n emp.ssn%type,p_na emp.name%type,p_dn emp.deptno%type)
8 is
9 begin
10 insert into emp (ssn,name,deptno) values(p_n,p_na,p_dn);
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:
Application trigger: fires whenever an event occurs with a particular application
Database trigger: fires whenever a data event or system event occurs on a schema or database.
A triggering statement contains:
Triggering timing
o For table: BEFORE, AFTER
o For view: INSTEAD OF
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
create trigger ab
before insert or delete or update on a
for each row
begin
raise_application_error(-20000,'not accessible')
end
This program raises an error during insertion and deletion and update operation in a row.
_____________________________________________________________________
104