0% found this document useful (0 votes)
32 views61 pages

Oracle Project Final 1

project

Uploaded by

Er Pradip Patel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views61 pages

Oracle Project Final 1

project

Uploaded by

Er Pradip Patel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 61

1

CREATE TABLE STATEMENT:-QUERY:- Create a table student_record with the following fields:Column name
Name
Class
Roll no

type
Varchar2
Varchar2
number

Size
20
15
4

Total marks

number

description
Name of the student
Class of the student
Roll no of the
student
Total marks of the
student

SQL> Create table student_record


2(
3 name varchar2 (20),
4 class varchar2 (15),
5 roll no number (4),
6 total marks number (2));
Table created.
=================================================
The contents of the table can be viewed as:-SQL> describe student_record;
Name
Null?
Type
----------------------------------------- -------- ---------NAME
VARCHAR2 (20)
CLASS
VARCHAR2 (15)
ROLL_NO
NUMBER (4)
TOTAL_MARKS
NUMBER (2)
=================================================

TABLE CONSTRAINTS:-QUERY:- Add constraint primary key to the roll no field of


student record
SQL> alter table student_record
2 add constraint pk_roll_no primary key(roll_no);
Table altered.

QUERY:- Add constraint not null to the name field of student


record
SQL> alter table student_record
2 modify name varchar2 (20) not null;
Table altered.

QUERY:- Add constraint unique to the phone no field of student


record
SQL> alter table student_record
2 add phone no number (10) unique;
Table altered.
QUERY:- Add check constraint with total marks >33 in the table
student record
SQL> alter table student_record
2
add constraint ch_tm check(total_marks>33);
Table altered.

QUERY:- Add default marks 99 with the default constraint in


the table student record
SQL> alter table student_record
2 modify total_marks default 99;
Table altered.
================================================
The contents of the table can be viewed as:-SQL> describe student_record
Name
Null?
Type
----------------------------------------- -------- ---------------------------NAME
NOT NULL
VARCHAR2 (20)
CLASS
VARCHAR2 (15)
ROLL_NO
NOT NULL
NUMBER (4)
TOTAL_MARKS
NUMBER (2)
PHONE_NO
NUMBER (10)
======================================================

QUERY:- Add foreign key constraint to the dept no field of emp


table
SQL> describe emp;
Name
Null?
Type
----------------------------------------- -------- ---------------EMPNO
NOT NULL
NUMBER (4)
ENAME
VARCHAR2 (10)
JOB
VARCHAR2 (9)
MGR
NUMBER (4)
HIREDATE
DATE
SAL
NUMBER (7, 2)
COMM
NUMBER (7, 2)
DEPTNO
NUMBER (2)
SQL> describe dept;
Name
Null?
Type
----------------------------------------- -------- ---------------DEPTNO
NOT NULL
NUMBER (2)
DNAME
VARCHAR2 (14)
LOC
VARCHAR2 (13)
SQL> alter table emp
2 add constraint fk_deptno foreign key (deptno) references dept (deptno) on
delete cascade;
Table altered.
======================================================

Dropping a table:SQL> select * from tab;


TNAME
TABTYPE CLUSTERID
------------------------------ ------- ---------BONUS
TABLE
DEPT
TABLE
EMP
TABLE
SALGRADE
TABLE
STUDENT
TABLE
STUDENT_RECORD
TABLE
SUNNY
TABLE
7 rows selected.
SQL> drop table student;
Table dropped.
SQL> select * from tab;
TNAME
TABTYPE CLUSTERID
------------------------------ ------- ---------BONUS
TABLE
DEPT
TABLE
EMP
TABLE
SALGRADE
TABLE
STUDENT_RECORD
TABLE
SUNNY
TABLE
6 rows selected.

Renaming a table:QUERY:-Rename student_record to student


SQL> select * from tab;
TNAME
TABTYPE CLUSTERID
------------------------------ ------- ---------BONUS
TABLE
DEPT
TABLE
EMP
TABLE
SALGRADE
TABLE
STUDENT_RECORD
TABLE
SUNNY
TABLE
6 rows selected.
SQL> rename student_record to student;
Table renamed.
SQL> select * from tab;
TNAME
TABTYPE CLUSTERID
------------------------------ ------- ---------BONUS
TABLE
DEPT
TABLE
EMP
TABLE
SALGRADE
TABLE
STUDENT
TABLE
SUNNY
TABLE
6 rows selected.
======================================================

Inserting records into table:QUERY:-To insert a record into student table


SQL> insert into student
2 values ('ram','bba', 555, 66, 124356);
1 row created.

QUERY:-inserting data into specified columns


SQL> insert into student (name, class, roll_no) values ('shyam','bba', 444);
1 row created.

*the contents of the table can be viewed as:-SQL> select * from student;
NAME
CLASS
ROLL_NO TOTAL_MARKS PHONE_NO
-------------------- --------------- ---------- ----------- ---------Ram
bba
555
66
124356
Shyam
bba
444
99

QUERY:-inserting through parameter substitution


SQL> insert into student values ('&1','&2', &3, &4, &5);
Enter value for 1: Kate
Enter value for 2: bba2
Enter value for 3: 556
Enter value for 4: 98
Enter value for 5: 14356
Old 1: insert into student values ('&1','&2',&3,&4,&5)
New 1: insert into student values ('kate','bba2',556,98,14356)

1 row created
SQL> /
Enter value for 1: duplikate
Enter value for 2: bba2
Enter value for 3: 557
Enter value for 4: 89
Enter value for 5: 536475
Old 1: insert into student values ('&1','&2', &3, &4, &5)
New 1: insert into student values ('duplikate','bba2',557, 89,536475)
1 row created.

*the contents of the table can be viewed as:-SQL> select * from student;
NAME
CLASS
ROLL_NO TOTAL_MARKS PHONE_NO
-------------------- --------------- ---------- ----------- ---------Ram
bba
555
66
124356
Shyam
bba
444
99
Kate
bba2
556
98
14356
Duplikate
bba2
557
89
536475
======================================================

Updating records into table:SQL> update student set name='pkate' where roll no=444;
1 row updated.
SQL> select * from student;
NAME
CLASS
ROLL_NO TOTAL_MARKS PHONE_NO
-------------------- --------------- ---------- ----------- ---------Ram
bba
555
66
124356
Pkate
bba
444
99
Kate
bba2
556
98
14356
Duplikate
bba2
557
89
536475
SQL> update student set name='sam', phone_no=653487 where roll no=444;
1 row updated.

*the contents of the table can be viewed as:-SQL> select * from student;
NAME
CLASS
ROLL_NO
TOTAL_MARKS PHONE_NO
-------------------- --------------- ---------- ----------- ---------Ram
bba
555
66
124356
Sam
bba
444
99
653487
Kate
bba2
556
98
14356
Duplikate
bba2
557
89
536475
======================================================

10

Deleting records from a table:QUERY:- delete the record where name =ram..
SQL> delete from student where name='ram';
1 row deleted.
SQL> select * from student;
NAME
CLASS
ROLL_NO TOTAL_MARKS PHONE_NO
-------------------- --------------- ---------- ----------- ---------Sam
bba
444
99
653487
Kate
bba2
556
98
14356
Duplikate
bba2
557
89
536475

QUERY:- deleting all records from a table.


SQL> select * from salgrade;
GRADE
LOSAL
---------- ---------- ---------1
700
2
1201
3
1401
4
2001
5
3001

HISAL
1200
1400
2000
3000
9999

SQL> delete salgrade;


5 rows deleted.
SQL> select * from salgrade;
No rows selected
======================================================

11

Savepoint and rollback:SQL> select * from student;


NAME
CLASS
ROLL_NO TOTAL_MARKS PHONE_NO
-------------------- --------------- ---------- ----------- ---------Sam
bba
444
99
653487
Kate
bba2
556
98
14356
Duplikate
bba2
557
89
536475
SQL> insert into student values ('peter','bba2', 559, 78, 1272583);
1 row created.
SQL> savepoint flag_of_khan;
Savepoint created.
SQL> select * from student;
NAME
CLASS
ROLL_NO TOTAL_MARKS
-------------------- --------------- ---------- ----------- ---------Sam
bba
444
99
Kate
bba2
556
98
Duplikate
bba2
557
89
Peter
bba2
559
78
SQL> update student set name='repeater' where roll no=559;
1 row updated.
SQL> select * from student;

PHONE_NO
653487
14356
536475
1272583

12

NAME
CLASS
ROLL_NO TOTAL_MARKS
-------------------- --------------- ---------- ----------- ---------Sam
bba
444
99
Kate
bba2
556
98
Duplikate
bba2
557
89
Repeater
bba2
559
78

PHONE_NO
653487
14356
536475
1272583

SQL> rollback to savepoint flag_of_khan;


Rollback complete.
SQL> select * from student;
NAME
CLASS
ROLL_NO TOTAL_MARKS PHONE_NO
-------------------- --------------- ---------- ----------- ---------Sam
bba
444
99
653487
Kate
bba2
556
98
14356
Duplikate
bba2
557
89
536475
Peter
bba2
559
78
1272583
======================================================

13

The select statement:Query:-select name from student where roll no=557


SQL> select student.name from student where roll_no=557;
NAME
-------------------Duplikate

Query:-select name from student.


SQL> select student.name from student;
NAME
-------------------Sam
Kate
Duplikate
Peter

14

Elimination of duplicate records with distinct


clause:SQL> select distinct roll_no,name from student;
ROLL_NO NAME
---------- -------------------444 Sam
556
Kate
557
Duplikate
559
Peter

The Oracle table dual


SQL> select 2*2 from dual;
2*2
---------4
SQL> select sysdate from dual;
SYSDATE
--------21-FEB-13

15

Working with operators:Relational operators..


SQL> select name, class, total_marks
2 from student where roll_no=559;
NAME
CLASS
TOTAL_MARKS
-------------------- --------------- ----------Peter
bba2
78
SQL> select * from student where total marks>90;
NAME
CLASS
ROLL_NO TOTAL_MARKS PHONE_NO
-------------------- --------------- ---------- ----------- ---------Sam
bba
444
99
653487
Kate
bba2
556
98
14356

Logical operators.
SQL> select name, total_marks, roll_no from student where class='bba2'
AND phone no=14356;
NAME
TOTAL_MARKS
-------------------- ----------- ---------Kate
98

ROLL_NO
556

SQL> select * from student where class='bba2' OR total_marks>90;

16

NAME
CLASS
ROLL_NO TOTAL_MARKS PHONE_NO
-------------------- --------------- ---------- ----------- ---------Sam
bba
444
99
653487
Kate
bba2
556
98
14356
Duplikate
bba2
557
89
536475
Peter
bba2
559
78
1272583
SQL> select name, class from student where NOT (class='bba');
NAME
CLASS
-------------------- --------------Kate
bba2
Duplikate
bba2
Peter
bba2

Special operators
SQL> select name, class from student where total_marks
100;
NAME
CLASS
-------------------- --------------Sam
bba
Kate
bba2

between 90 and

17

SQL> select * from student where roll_no IN (550,557);


NAME
CLASS
ROLL_NO TOTAL_MARKS PHONE_NO
-------------------- --------------- ---------- ----------- ---------Duplikate
bba2
557
89
536475
SQL> select * from student where name not

in ('Kate, Sam');

NAME
CLASS
ROLL_NO TOTAL_MARKS PHONE_NO
-------------------- --------------- ---------- ----------- ---------Duplikate
bba2
557
89
536475
Peter
bba2
559
78
1272583

18

Working with null values:-SQL> insert into student (name, roll_no) values ('lavika', 578);
1 row created.
SQL> select * from student;
NAME
CLASS
ROLL_NO TOTAL_MARKS
-------------------- --------------- ---------- ----------- ---------Sam
bba
444
99
Kate
bba2
556
98
Duplikate
bba2
557
89
Peter
bba2
559
78
Diksha
bba
558
99
Smita
567
97
Lavika
578
99
7 rows selected.
SQL> select name from student where phone_no is null;
NAME
-------------------Smita
Lavika

PHONE_NO
653487
14356
536475
1272583
243564

19

Order by clause:query:SQL> select name, total_marks from student order by total_marks;


NAME
TOTAL_MARKS
-------------------- ----------Peter
78
Duplikate
89
Smita
97
Kate
98
Sam
99
Diksha
99
Lavika
99
7 rows selected

query:SQL> select name, roll_no from student order by roll_no desc;


NAME
ROLL_NO
-------------------- ---------Lavika
578
Smita
567
Peter
559
Diksha
558
Duplikate
557
Kate
556
Sam
444
7 rows selected.

20

query:SQL> select name, class, roll_no from student order by 3;


NAME
CLASS
ROLL_NO
-------------------- --------------- ---------Sam
bba
444
Kate
bba2
556
Duplikate
bba2
557
Diksha
bba
558
Peter
bba2
559
Smita
567
Lavika
578
7 rows selected.

query:SQL> select name, roll_no, total_marks from student order by roll_no asc,
total_marks desc;
NAME
ROLL_NO TOTAL_MARKS
-------------------- ---------- ----------Sam
444
99
Kate
556
98
Duplikate
557
89
Diksha
558
99
Peter
559
78
Smita
567
97
Lavika
578
99
7 rows selected.
======================================================

21

Pattern matching:query:SQL> select name, total_marks from student where name like '%Kate';
NAME
TOTAL_MARKS
-------------------- ----------Kate
98
Duplikate
89

query:SQL> select name, class from student where name like '_____';
NAME
CLASS
-------------------- --------------Peter
bba2
Smita

Column Concatenation:-query:SQL> select 'roll number of '||name|| ' is '||roll_no from student;
'ROLLNUMBEROF'||NAME||'IS'||ROLL_NO
------------------------------------------------------------------------------Roll number of Sam is 444
Roll number of Kate is 556
Roll number of duplikate is 557
Roll number of peter is 559
Roll number of diksha is 558
Roll number of smita is 567
Roll number of lavika is 578
7 rows selected.

22

Set Operators:The union operator.


query:SQL> select name, class from student where class='bba'
2 union
3 select name, class from student where class='bba2';
NAME
CLASS
-------------------- --------------Diksha
bba
Duplikate
bba2
Kate
bba2
Peter
bba2
Sam
bba

The intersect operator.


query:SQL> select total_marks from student where class='bba'
2 intersect
3 select total_marks from student where class is null;
TOTAL_MARKS
----------99

23

FUNCTIONS AND GROUP BY CLAUSE


SINGLE-ROW FUNCTIONS
CHARACTER FUNCTIONS

ascii(string)

SQL> select ascii('h') from dual;


ASCII('H')
---------104

chr(x)

SQL> select chr(98) "first", chr(100) "second" from dual;


fs
-bd

concat(x1,x2)

SQL> select concat('henry','ford') as name from dual;


NAME
--------henryford

instr(string/column name,x)

SQL> select instr('anamika','a') as position from dual;


POSITION
---------1

length(x)

SQL> select length('my name is khan') as length from dual;


LENGTH
---------15

24

lpad(char1,n,[char2])

SQL> select lpad(name,10,' '),lpad(name,10,'*') from student;


LPAD(NAME, LPAD(NAME,
---------- ---------sam *******sam
kate ******kate
duplikate *duplikate
peter *****peter
diksha ****diksha
smita *****smita
lavika ****lavika
7 rows selected.

ltrim(string[,char(s)])

SQL> select ltrim(name,'s'),ltrim(name) from student;


LTRIM(NAME,'S')
LTRIM(NAME)
-------------------- -------------------am
sam
kate
kate
duplikate
duplikate
peter
peter
diksha
diksha
mita
smita
lavika
lavika
7 rows selected.

rpad(char1,n[,char2])

SQL> select rpad(name,10,' '),rpad(name,10,'*')from student;


RPAD(NAME, RPAD(NAME,
---------- ---------sam
sam*******
kate
kate******
duplikate duplikate*
peter
peter*****
diksha diksha****
smita
smita*****
lavika lavika****

25
7 rows selected.

rtrim(string[,char(s)])

SQL> select rtrim(name,'a'),rtrim(name) from student;


RTRIM(NAME,'A')
RTRIM(NAME)
-------------------- -------------------sam
sam
kate
kate
duplikate
duplikate
peter
peter
diksh
diksha
smit
smita
lavik
lavika
7 rows selected.

replace(<c1>,<c2>[,<c3>])

SQL> select replace ('uptown','up','down') from dual;


REPLACE(
-------downtown

substr(z,x[,y])

SQL> select substr('abcdefgh',2,5) "first" ,substr('abcdefgh',2) "second" from dual;


first second
----- ------bcdef bcdefgh
SQL> select substr('abcdefgh',-3)from dual;
SUB
--fgh

26

CASE CONVERSION FUNCTIONS

initcap(string)

SQL> select initcap(name)from student;


INITCAP(NAME)
-------------------Sam
Kate
Duplikate
Peter
Diksha
Smita
Lavika
7 rows selected.

lower(string)

SQL> select lower(name) from student;


LOWER(NAME)
-------------------sam
kate
duplikate
peter
diksha
smita
lavika
7 rows selected.

upper(string)

SQL> select upper(name) from student;


UPPER(NAME)
-------------------SAM
KATE
DUPLIKATE
PETER
DIKSHA
SMITA
LAVIKA

27

7 rows selected.

translate(char,find,new)

SQL> select name,translate(name,'a',2)from student;


NAME
TRANSLATE(NAME,'A',2
-------------------- -------------------sam
s2m
kate
k2te
duplikate
duplik2te
peter
peter
diksha
diksh2
smita
smit2
lavika
l2vik2
7 rows selected.

28

NUMERIC FUNCTIONS

abs(x)

SQL> select abs(-10) "absolute" from dual;


absolute
---------10

ceil(x)

SQL> select ceil (9.8), ceil(-32.85), ceil(0) from dual;


CEIL(9.8) CEIL(-32.85) CEIL(0)
---------- ------------ ---------10
-32
0

cos(x)

SQL> select cos(45) from dual;


COS(45)
---------.525321989

exp(X)

SQL> select exp(4) from dual;


EXP(4)
---------54.59815

floor(x)

SQL> select floor(9.8), floor(-32.5), floor(137) from dual;


FLOOR(9.8) FLOOR(-32.5) FLOOR(137)
---------- ------------ ---------9
-33
137

mod(x,y)

SQL> select mod(10,3) as first,mod(10,5) as second from dual;


FIRST SECOND
---------- ----------

29
1

power(x,y)

SQL> select power(2,3) "power" from dual;


power
---------8

round(x[,y])

SQL> select round(55.849,1),round(55.849) from dual;


ROUND(55.849,1) ROUND(55.849)
--------------- ------------55.8
56

sign(x)

SQL> select sign(-2),sign(2) from dual;


SIGN(-2) SIGN(2)
---------- ----------1
1

sqrt(x)

SQL> select sqrt(36) as sqroot from dual;


SQROOT
---------6

trunc(x,n)

SQL> select trunc(32.934,2),trunc(32.934),trunc(32.934,-1) from dual;


TRUNC(32.934,2) TRUNC(32.934) TRUNC(32.934,-1)
--------------- ------------- ---------------32.93
32
30
===============================================================

30

DATE FUNCTIONS

sysdate

SQL> select sysdate from dual;


SYSDATE
--------22-FEB-13

add_months(date,n)

SQL> select add_months('15-mar-2012',26) from dual;


ADD_MONTH
--------15-MAY-14

last_day(date)

SQL> select last_day('10-feb-13') from dual;


LAST_DAY(
--------28-FEB-13

months_between(date1,date2)

SQL> select months_between('15-mar-20','26-jan-12') from dual;


MONTHS_BETWEEN('15-MAR-20','26-JAN-12')
--------------------------------------97.6451613

next_day(date,char)

SQL> select next_day('01-sep-93','friday')as "date" from dual;


date
--------03-SEP-93

31

GENERAL FUNCTIONS

Greatest(expr1[,expr2]...)

SQL> select greatest(-2,5,8) from dual;


GREATEST(-2,5,8)
---------------8

least(expr1[,expr2]...)

SQL> select least('ABCD','abcd','xyz') from dual;


LEAS
---ABCD

NVL(col,value)

SQL> select name, class , total_marks+nvl(phone_no,0) "sum" from student;


NAME
CLASS
sum
-------------------- --------------- ---------sam
bba
653586
kate
bba2
14454
duplikate
bba2
536564
peter
bba2
1272661
diksha
bba
243663
smita
97
lavika
99
7 rows selected.

UID

SQL> select uid from dual;


UID
---------66

User

SQL> select user from dual;


USER
-----------------------------SCOTT

32

AGGREGATE FUNCTIONS

count(x)

QUERY:- To display the total no. of total_marks


SQL> select count(total_marks) from student;
COUNT(TOTAL_MARKS)
-----------------7

QUERY:- To list the number of different total_marks in the


student_record table
SQL> select count(distinct total_marks) from student;
COUNT(DISTINCTTOTAL_MARKS)
-------------------------5

sum(x)

QUERY:- To add the total_marks


SQL> select sum(total_marks) from student;
SUM(TOTAL_MARKS)
---------------659

avg(x)

QUERY:- To calculate the average of total_marks in the


student_record table
SQL> select avg(total_marks) from student;
AVG(TOTAL_MARKS)
---------------94.1428571

33

min(x)

QUERY:- To list the minimum total_marks


SQL> select min(total_marks) from student;
MIN(TOTAL_MARKS)
---------------78

max(x)

QUERY:- To list the maximum total_marks


SQL> select max(total_marks) from student;
MAX(TOTAL_MARKS)
---------------99

QUERY:- To display the use of avg, sum, min and max together
SQL> select avg(total_marks), sum(total_marks), min(total_marks), max(total_marks) from student;
AVG(TOTAL_MARKS) SUM(TOTAL_MARKS) MIN(TOTAL_MARKS) MAX(TOTAL_MARKS)
---------------- ---------------- ---------------- ---------------94.1428571
659
78
99

GROUP BY CLAUSE
QUERY:- To list the sum of total_marks of each class in
student_record table
SQL> select class, sum(total_marks) from student group by class;
CLASS
SUM(TOTAL_MARKS)
--------------- ---------------bba
198
bba2
265
196

34

QUERY:- To list the sum of salary of each job and deptno in emp
table
SQL> select deptno, job, sum(sal) from emp group by deptno, job;
DEPTNO JOB
SUM(SAL)
---------- --------- ---------10 CLERK
1300
10 MANAGER
2450
10 PRESIDENT
5000
20 ANALYST
6000
20 CLERK
1900
20 MANAGER
2975
30 CLERK
950
30 MANAGER
2850
30 SALESMAN
5600
9 rows selected.

HAVING CLAUSE
QUERY:- To find the maximum salary of each department, but
show only the departments that have a maximum salary of more
than Rs.2000
SQL> select deptno,max(sal) from emp group by deptno having max(sal)>2000;
DEPTNO MAX(SAL)
---------- ---------10
5000
20
3000
30
2850

QUERY:- To the total salary, max and min salary and the average
salary of employee's jobwise, for deptno 20 and display only those
rows having average salary greater than 1000
SQL> select job, sum(sal), avg(sal), max(sal), min(sal) from emp
2 where deptno=20
3 group by job
4 having avg(sal)>1000;
JOB
SUM(SAL) AVG(SAL) MAX(SAL) MIN(SAL)
--------- ---------- ---------- ---------- ---------ANALYST
6000
3000
3000
3000
MANAGER
2975
2975
2975
2975

35

JOINS AND SUBQUERIES


EQUI JOIN:QUERY:- TO list the employee name with their department names
SQL> select ename,dname from emp,dept where emp.deptno=dept.deptno;
ENAME
DNAME
---------- -------------SMITH
RESEARCH
ALLEN
SALES
WARD
SALES
JONES
RESEARCH
MARTIN SALES
BLAKE
SALES
CLARK ACCOUNTING
SCOTT RESEARCH
KING
ACCOUNTING
TURNER SALES
ADAMS
RESEARCH
ENAME
DNAME
---------- -------------JAMES
SALES
FORD
RESEARCH
MILLER ACCOUNTING
14 rows selected.

36

CARTESIAN JOIN:QUERY:- TO list the employee name from emp table and
department names from dept table
SQL> select name,dname from student,dept;
NAME
DNAME
-------------------- -------------sam
ACCOUNTING
kate
ACCOUNTING
duplikate
ACCOUNTING
peter
ACCOUNTING
diksha
ACCOUNTING
smita
ACCOUNTING
lavika
ACCOUNTING
sam
RESEARCH
kate
RESEARCH
duplikate
RESEARCH
peter
RESEARCH
NAME
DNAME
-------------------- -------------diksha
RESEARCH
smita
RESEARCH
lavika
RESEARCH
sam
SALES
kate
SALES
duplikate
SALES
peter
SALES
diksha
SALES
smita
SALES
lavika
SALES
sam
OPERATIONS
NAME
DNAME
-------------------- -------------kate
OPERATIONS
duplikate
OPERATIONS
peter
OPERATIONS
diksha
OPERATIONS
smita
OPERATIONS
lavika
OPERATIONS
28 rows selected.

37

OUTER JOIN:QUERY:- TO list the employees working in each department.


display the department details even if no employee belongs to that
department
SQL> select empno,ename,emp.deptno,dname,loc from emp,dept where emp.deptno(+)=dept.deptno;
EMPNO ENAME
DEPTNO DNAME
LOC
---------- ---------- ---------- -------------- ------------7782 CLARK
10 ACCOUNTING NEW YORK
7839 KING
10 ACCOUNTING NEW YORK
7934 MILLER
10 ACCOUNTING NEW YORK
7369 SMITH
20 RESEARCH
DALLAS
7876 ADAMS
20 RESEARCH
DALLAS
7902 FORD
20 RESEARCH
DALLAS
7788 SCOTT
20 RESEARCH
DALLAS
7566 JONES
20 RESEARCH
DALLAS
7499 ALLEN
30 SALES
CHICAGO
7698 BLAKE
30 SALES
CHICAGO
7654 MARTIN
30 SALES
CHICAGO
EMPNO ENAME
DEPTNO DNAME
LOC
---------- ---------- ---------- -------------- ------------7900 JAMES
30 SALES
CHICAGO
7844 TURNER
30 SALES
CHICAGO
7521 WARD
30 SALES
CHICAGO
OPERATIONS BOSTON
15 rows selected.

38

SELF JOIN:QUERY:- TO list the names of the manager with the employee
record
SQL> select worker.ename "ename" ,manager.ename "manager"
2 from emp worker,emp manager
3 where worker.mgr=manager.empno;
ename
manager
---------- ---------SMITH
FORD
ALLEN
BLAKE
WARD
BLAKE
JONES
KING
MARTIN BLAKE
BLAKE
KING
CLARK
KING
SCOTT JONES
TURNER BLAKE
ADAMS
SCOTT
JAMES
BLAKE
ename
manager
---------- ---------FORD
JONES
MILLER CLARK
13 rows selected.

39

NESTED QUERIES
QUERY:- TO list the name of the employees who do the same job
as that of an employee number 7369
SQL> select ename,job from emp
2 where job=(select job from emp where empno=7369);
ENAME
JOB
---------- --------SMITH
CLERK
ADAMS
CLERK
JAMES
CLERK
MILLER CLERK

QUERY:- TO list the name and salary of the employee who gets
salary greater than the minimum salary in the employee table
SQL> SELECT ENAME,SAL FROM EMP WHERE SAL>(SELECT MIN(SAL) FROM EMP);
ENAME
SAL
---------- ---------ALLEN
1600
WARD
1250
JONES
2975
MARTIN
1250
BLAKE
2850
CLARK
2450
SCOTT
3000
KING
5000
TURNER
1500
ADAMS
1100
JAMES
950
ENAME
SAL
---------- ---------FORD
3000
MILLER
1300
13 rows selected.

40

QUERY:- TO list the employee name and salary of the employee


whose salary is greater than the average salary of employees whose
hiredate is before 01-jan-81
SQL> select ename,sal from emp
2 where sal>(select avg(sal)from emp where hiredate < '01-jan-81');
ENAME
SAL
---------- ---------ALLEN
1600
WARD
1250
JONES
2975
MARTIN
1250
BLAKE
2850
CLARK
2450
SCOTT
3000
KING
5000
TURNER
1500
ADAMS
1100
JAMES
950
ENAME
SAL
---------- ---------FORD
3000
MILLER
1300
13 rows selected.

QUERY:- TO list the job with highest average salary


SQL> select job,avg(sal)
2 from emp group by job
3 having avg(sal)=(select max (avg(sal))
4 from emp group by job);
JOB
AVG(SAL)
--------- ---------PRESIDENT
5000

41

QUERY:- TO list the employee name,salary and deptno of the


employees who earn the same salary as the minimum salary for
different departments
SQL> select ename,sal,deptno from emp
2 where sal IN(select min(sal) from emp group by deptno);
ENAME
SAL DEPTNO
---------- ---------- ---------SMITH
800
20
JAMES
950
30
MILLER
1300
10

OR
SQL> select ename,sal,deptno from emp
2 where sal IN(800,950,1300);
ENAME
SAL DEPTNO
---------- ---------- ---------SMITH
800
20
JAMES
950
30
MILLER
1300
10

QUERY:- TO list empno and name whose salary is greater than the
average salary of all the departments
SQL> select empno,ename,job from emp where sal>ALL (select avg(sal) from emp group by deptno);
EMPNO ENAME
JOB
---------- ---------- --------7566 JONES
MANAGER
7788 SCOTT ANALYST
7839 KING
PRESIDENT
7902 FORD
ANALYST

QUERY:- TO list name,empno and manager of the employees


whose mgr=7902 but not the manager himself.
SQL> select ename,empno,mgr from emp
2 where (job,deptno) IN (select job,deptno from emp where mgr=7902)AND mgr<> 7902;
ENAME
EMPNO
MGR
---------- ---------- ---------ADAMS
7876
7788

42

QUERY:- TO list the employee details of those employees whose


salary is greater than any of the nmanagers
SQL> select empno,ename,sal from emp
2 where sal>ANY(select sal from emp where job='MANAGER');
EMPNO ENAME
SAL
---------- ---------- ---------7566 JONES
2975
7698 BLAKE
2850
7788 SCOTT
3000
7839 KING
5000
7902 FORD
3000

VIEWS
QUERY:- To create a view for the clerk
SQL> create view clerk as select * from emp where job='CLERK';
View created.

To describe the view


SQL> SELECT * FROM CLERK;
EMPNO ENAME JOB
MGR HIREDATE
SAL
---------- ---------- --------- ---------- --------- ---------- ---------DEPTNO
---------7369 SMITH
CLERK
7902 17-DEC-80
800
20
7876 ADAMS
20
7900 JAMES
30

CLERK
CLERK

7788 23-MAY-87
7698 03-DEC-81

COMM

1100
950

EMPNO ENAME JOB


MGR HIREDATE
SAL
---------- ---------- --------- ---------- --------- ---------- ---------DEPTNO
---------7934 MILLER CLERK
7782 23-JAN-82
1300
10

COMM

43

SEQUENCES
QUERY:- Create a sequence 'empnumber' starting with value 100
and incremented by 2
SQL> create sequence empcode increment by 2 start with 100;
Sequence created.

QUERY:- To view the next number in sequence


SQL> select empcode.nextval from dual;
NEXTVAL
---------100

QUERY:- To drop the sequence


SQL> drop sequence empcode;
Sequence dropped.

ROLES AND PRIVILEGES


CREATION OF USER ACCOUNTS
QUERY:- To create a user account
SQL> connect system/manager;
Connected.
SQL> create user tom identified by jerry;
User created.

44

QUERY:- To view whether the user has been created


SQL> select * from all_users;
USERNAME
USER_ID CREATED
------------------------------ ---------- --------SYS
0 04-SEP-01
SYSTEM
5 04-SEP-01
OUTLN
11 04-SEP-01
DBSNMP
17 04-SEP-01
ORDSYS
29 04-SEP-01
AURORA$JIS$UTILITY$
26 04-SEP-01
OSE$HTTP$ADMIN
27 04-SEP-01
AURORA$ORB$UNAUTHENTICATED
28 04-SEP-01
OLAPSVR
39 04-SEP-01
OLAPSYS
37 04-SEP-01
ORDPLUGINS
30 04-SEP-01
USERNAME
USER_ID CREATED
------------------------------ ---------- --------MDSYS
31 04-SEP-01
CTXSYS
32 04-SEP-01
WKSYS
34 04-SEP-01
OLAPDBA
40 04-SEP-01
QS_CBADM
62 04-SEP-01
QS_ADM
57 04-SEP-01
QS
58 04-SEP-01
QS_WS
59 04-SEP-01
HR
53 04-SEP-01
OE
54 04-SEP-01
PM
55 04-SEP-01
USERNAME
USER_ID CREATED
------------------------------ ---------- --------SH
56 04-SEP-01
QS_ES
60 04-SEP-01
QS_OS
61 04-SEP-01
RMAN
65 04-SEP-01
QS_CB
63 04-SEP-01
QS_CS
64 04-SEP-01
SCOTT
66 04-SEP-01
TOM
67 23-FEB-13
30 rows selected.

45

QUERY:- To alter user account by changing its password


SQL> alter user tom IDENTIFIED BY jerry2;
User altered.

QUERY:- To drop user account


SQL> connect system/manager;
Connected.
SQL> drop user tom cascade;
User dropped.

PRIVILEGES
QUERY:- To grant all the permissions to the user 'peter'
SQL> create user peter IDENTIFIED BY repeater;
User created.
SQL> grant create session to peter;
Grant succeeded.
OR
SQL> grant connect,resource to peter;
Grant succeeded.

QUERY:- To describe the privileges granted to the user 'peter'


SQL> connect peter/repeater;
Connected.
SQL> create table ruchi
2 (
3 name varchar2(100)
4 );
Table created.

46

QUERY:- To grant 'peter' select permission on 'emp' table


SQL> connect scott/tiger;
Connected.
SQL> grant select on emp to peter;
Grant succeeded.

QUERY:- To revoke the privilege of select from 'peter'


SQL> connect scott/tiger;
Connected.
SQL> revoke select on emp from peter;
Revoke succeeded.

ROLES
QUERY:- To create a role
SQL> connect system/manager;
Connected.
SQL> create role myrole1 identified by myrole;
Role created.

QUERY:- To grant connect and resource role to 'myrole1'


SQL> grant connect ,resource to myrole1;
Grant succeeded.

QUERY:- To delete the role 'myrole1'


SQL> connect system/manager;
Connected.
SQL> drop role myrole1;
Role dropped.

47

PL/SQL PROGRAMS:// Program to multiply two numbers.


SQL> connect system/manager;
Connected.
SQL> set serveroutput on;
SQL> declare
2 val1 number;
3 val2 number:=10;
4 result number;
5 begin
6 val1:=20;
7 result:=val1*val2;
8 dbms_output.put_line ('product of '||val1||' and '||val2||' is '||result);
9 end;
10 /
OUTPUT:
Product of 20 and 10 is 200
PL/SQL procedure successfully completed.

48

// Program to find area of a circle.


SQL> set serveroutput on;
SQL> declare
2 r number;
3 pi number:=3.14;
4 a number;
5 begin
6 r:=&r;
7 a:=pi*r*r;
8 dbms_output.put_line ('area of circle with radius '||r||' is '||a);
9 end;
10 /
OUTPUT:
Enter value for r: 7
Old 6: r:=&r;
New 6: r:=7;
Area of circle with radius 7 is 153.86
PL/SQL procedure successfully completed.

49

// Program to find whether a given no. is even or not.


SQL> set serveroutput on;
SQL> declare
2 n numbers;
3 begin
4 n:= &n;
5 if (n mod 2 = 0 ) then
6 dbms_output.put_line (n||' is even');
7 end if;
8 end;
9 /
OUTPUT:
Enter value for n: 4
Old 4:
n := &n;
New 4: n := 4;
4 is even
PL/SQL procedure successfully completed.

50

// Program to show the use of exit


SQL> set serveroutput on;
SQL> declare
2 n number:=0;
3 begin
4 loop
5 n:=n+1;
6 if (n>4) then
7 exit;
8 end if;
9 end loop;
10 dbms_output.put_line('loop executes '||n||' times ');
11 end;
12 /

Output:
loop executes 5 times
PL/SQL procedure successfully completed.

51

// Program to find grade of student.


SQL> set serveroutput on;
SQL> declare
2 n number;
3 g char;
4 begin
5 n:=&n;
6 if (n>=80) then
7 dbms_output.put_line('grade is a ');
8 elsif((n>60) and (n<80)) then
9 dbms_output.put_line(' grade is b ');
10 elsif((n>45) and (n<60)) then
11 dbms_output.put_line(' grade is c ');
12 else
13 dbms_output.put_line(' fail ');
14 end if;
15 end;
16 /

Output:
Enter value for n: 85
Old 5: n:=&n;
New 5: n:=85;
Grade is a
PL/SQL procedure successfully completed.

52

// Program to print values from n to 1 using while


SQL> set serveroutput on;
SQL> declare
2 n number;
3 begin
4 n:=&n;
5 while(n>0) loop
6 dbms_output.put_line(n);
7 n:=n-1;
8 end loop;
9 end;
10 /

Output:
Enter value for n: 5
Old 4: n:=&n;
New 4: n:=5;
5
4
3
2
1
PL/SQL procedure successfully completed.

53

// Program to print values from 1 to n.


SQL> set serveroutput on;
SQL> declare
2 n number;
3 begin
4 n:=&n;
5 for i in 1..n loop
6 dbms_output.put_line(i);
7 end loop;
8 end;
9 /

Output:
Enter value for n: 5
Old 4: n:=&n;
New 4: n:=5;
1
2
3
4
5
PL/SQL procedure successfully completed.

54

// Program to print values from n to 1 using for loop


SQL> set serveroutput on;
SQL> declare
2 n number;
3 begin
4 n:=&n;
5 for i in reverse 1..n loop
6 dbms_output.put_line(i);
7 end loop;
8 end;
9 /

Output:
Enter value for n: 7
Old 4: n:=&n;
New 4: n:=7;
7
6
5
4
3
2
1
PL/SQL procedure successfully completed.

55

// Program to print a table


SQL> set serveroutput on;
SQL> declare
2 n number;
3 begin
4 n:=&n;
5 for i in 1..10 loop
6 dbms_output.put_line(n||'* '||i||' = '||n*i);
7 end loop;
8 end;
9 /

Output:
Enter value for n: 4
Old 4: n:=&n;
New 4: n:=4;
4* 1 = 4
4* 2 = 8
4* 3 = 12
4* 4 = 16
4* 5 = 20
4* 6 = 24
4* 7 = 28
4* 8 = 32
4* 9 = 36
4* 10 = 40
PL/SQL procedure successfully completed.

56

EXCEPTION HANDLING:-// PROGRAM THAT HANDLES TOO_MANY_ROWS


EXCEPTIONS
SQL> SET SERVEROUTPUT ON
SQL> declare
2 name dept.dname %type;
3 begin
4 select dname into name from dept
5 where deptno=10;
6 dbms_output.put_line('employee name := '||name);
7 exception
8 when too_many_rows then
9 dbms_output.put_line('more than one row returned');
10 end;
11 /
employee name := ACCOUNTING
PL/SQL procedure successfully completed.

57

//PROGRAM THAT HANDLES MORE THAN ONE


EXCEPTION...
SQL> set serveroutput on;
SQL> declare
2 name dept.dname %type;
3 begin
4 select dname into name from dept
5 where deptno=10;
6 dbms_output.put_line('employee name := '||name);
7 exception
8 when too_many_rows then
9 dbms_output.put_line('more than one row returned');
10 when zero_divide then
11 dbms_output.put_line('divide by zero');
12 when others then
13 dbms_output.put_line('no rows exist');
14 end;
15 /
employee name := ACCOUNTING
PL/SQL procedure successfully completed.

58

// USER DEFINED EXCEPTION THAT CHECKS WHETHER


THE NAME OF EMPLOYEE IS BLANK OR NOT DURING
INSERTION.....
SQL> set serveroutput on;
SQL> declare
2 ecode emp.empno %type;
3 name emp.ename %type;
4 ename_err exception;
5 begin
6 ecode := &ecode;
7 name := '&name';
8 if name is null then
9 raise ename_err;
10 end if;
11 insert into emp(empno,ename)values
12 (ecode,name);
13 dbms_output.put_line('data entered');
14 exception
15 when ename_err then
16 dbms_output.put_line('ename should not be blank');
17 end;
18 /
Enter value for ecode: 123
old 6: ecode := &ecode;
new 6: ecode := 123;
Enter value for name: abc
old 7: name := '&name';
new 7: name := 'abc';
data entered
PL/SQL procedure successfully completed.

59

//PRAGMA EXCEPTION INIT....


SQL> set serveroutput on;
SQL> declare
2 child_rec_present exception;
3 pragma exception_init(child_rec_present,-2292);
4 begin
5 delete from department where deptno=10;
6 dbms_output.put_line('data entered');
7 exception
8 when child_rec_present then
9 dbms_output.put_line('first remove child record');
10 end;
11 /
data entered
PL/SQL procedure successfully completed.

60

//USING SQL CODE AND SQL ERR MSG..


SQL> set serveroutput on;
SQL> declare
2 salary number;
3 ecode emp.empno %type;
4 begin
5 ecode := &ecode;
6 select sal into salary from emp
7 where empno= ecode;
8 dbms_output.put_line(salary);
9 exception
10 when others then
11 dbms_output.put_line
12 ('error code'||sqlcode);
13 dbms_output.put_line('error message'||sqlerrm);
14 end;
15 /
Enter value for ecode: 123
old 5: ecode := &ecode;
new 5: ecode := 123;
error code100
error messageORA-01403: no data found
PL/SQL procedure successfully completed.

61

//EXCEPTION PROPAGATION....
SQL> set serveroutput on;
SQL> declare
2 salary number;
3 e number;
4 begin
5 e :=&e;
6 select sal into salary from emp where empno=e;
7 if salary>4000 then
8 raise greater_sal;
9 end if;
10 dbms_output.put_line(salary);
11 exception
12 when no_data_found then
13 dbms_output.put_line('empno doesn't exist');
14 end;
15 exception
16 when greater_sal then
17 dbms_output.put_line('salary is greater than 4000');
18 end;
19 /
Enter value for e: 123
old 5: e :=&e;
new 5: e :=123;
ERROR:
ORA-01756: quoted string not properly terminated

You might also like