0% found this document useful (0 votes)
99 views86 pages

Dbms Lab Manual (R16)

The document outlines the objectives and experiments for a Database Management Systems lab course. The objectives are to introduce students to database concepts, SQL, PL/SQL, forms, and database design. The experiments cover skills with SQL queries, PL/SQL programming, form creation, and database connectivity. Tables are created for employees, departments, and salary grades to be used for the experiments.

Uploaded by

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

Dbms Lab Manual (R16)

The document outlines the objectives and experiments for a Database Management Systems lab course. The objectives are to introduce students to database concepts, SQL, PL/SQL, forms, and database design. The experiments cover skills with SQL queries, PL/SQL programming, form creation, and database connectivity. Tables are created for employees, departments, and salary grades to be used for the experiments.

Uploaded by

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

L T P

C
III Year – I Semester
0 0 3
2

DATA BASE MANAGEMENT SYSTEM LAB

OBJECTIVES:

• To provide a sound introduction to the discipline of database management as a subject in its own
right, rather than as a compendium of techniques and product-specific tools.

• To familiarize the participant with the nuances of database environments towards an


information-oriented data-processing oriented framework

• To give a good formal foundation on the relational model of data

• To present SQL and procedural interfaces to SQL comprehensively

• To give an introduction to systematic database design approaches covering conceptual design,


logical design and an overview of physical design

List of Experiments:

SQL

1. Queries to facilitate acquaintance of Built-In Functions, String Functions, Numeric Functions, Date
Functions and Conversion Functions.

2. Queries using operators in SQL

3. Queries to Retrieve and Change Data: Select, Insert, Delete, and Update

4. Queries using Group By, Order By, and Having Clauses

5. Queries on Controlling Data: Commit, Rollback, and Save point

6. Queries to Build Report in SQL *PLUS

7. Queries for Creating, Dropping, and Altering Tables, Views, and Constraints

8. Queries on Joins and Correlated Sub-Queries


9. Queries on Working with Index, Sequence, Synonym, Controlling Access, and Locking Rows for
Update, Creating Password and Security features.
PL/SQL

10. Write a PL/SQL Code using Basic Variable, Anchored Declarations, and Usage of
Assignment Operation

11. Write a PL/SQL Code Bind and Substitution Variables. Printing in PL/SQL

12. Write a PL/SQL block using SQL and Control Structures in PL/SQL

13. Write a PL/SQL Code using Cursors, Exceptions and Composite Data Types

14. Write a PL/SQL Code using Procedures, Functions, and Packages FORMS

15. Write a PL/SQL Code Creation of forms for any Information System such as Student Information
System, Employee Information System etc.

16. Demonstration of database connectivity

OUTCOMES:

•Understand, appreciate and effectively explain the underlying concepts of database technologies
• Design and implement a database schema for a given problem-domain
• Normalize a database
• Populate and query a database using SQL DML/DDL commands.
• Declare and enforce integrity constraints on a database using a state-of-the-artRDBMS
• Programming PL/SQL including stored procedures, stored functions, cursors, packages.
• Design and build a GUI application using a 4GL

Note: The creation of sample database for the purpose of the experiments is expected to be predecided
by the instructor.

Text Books/Suggested Reading:


1. Oracle: The Complete Reference by Oracle Press
2. Nilesh Shah, "Database Systems Using Oracle”, PHI, 2007.
3. Rick F Vander Lans, “Introduction to SQL”, Fourth Edition, Pearson Education, 2007
EMP TABLE
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
---------- ---------- -------- ---------- --------- -------- ----- ------
7369 smith clerk 7902 17-dec-80 800 20
7499 allen salesman 7698 20-feb-81 1600 300 30
7521 ward salesman 7698 22-feb-81 1250 500 30
7566 jones manager 7839 02-apr-81 2975 20
7654 martin salesman 7698 28-sep-81 1250 1400 30
7698 blake manager 7839 01-may-81 2850 30
7782 clark manager 7839 09-jan-81 2450 10
7788 scott analyst 7566 19-apr-87 3000 20
7839 king president 17-nov-81 5000 10
7844 turner salesman 7698 08-sep-81 10000 0 30
7876 adems clerk 7788 23-may-87 1100 20
7900 james clerk 7698 03-dec-81 950 30
7902 ford analyst 7566 03-dec-81 3000 20
7934 miller clerk 7782 23-jan-82 1300 10

DEPT TABLE
DEPTNO DNAME LOC
------ ---------- ----------
10 accounting newyork
20 research dallas
30 sales chicago
40 operations boston

SALGRADE TABLE

GRADE LOSAL HISAL

---------- ---------- ----------

1 700 1200

2 1201 1400

3 1401 2000

4 2001 3000

5 3001 9999
create table dept( deptno number(2) primary key,
2 dname varchar2(10) not null,
3 loc varchar2(8));

Table created.
SQL> desc dept
Name Null? Type
----------------------------------------- --------
DEPTNO NOT NULL NUMBER(2)
DNAME NOT NULL VARCHAR2(10)
LOC VARCHAR2(8)

SQL> insert into dept values(10,'accounting','newyork');


1 row created.
SQL> insert into dept values(20,'research','dallas');
1 row created.
SQL> insert into dept values(30,'sales','chicago');
1 row created.
SQL> insert into dept values(40,'operations','goston');
1 row created.

SQL> select *from dept;


DEPTNO DNAME LOC
---------- ---------- --------
10 accounting newyork
20 research dallas
13 sales chicago
40 operations goston

SQL> create table salgrade(grade number(5),losal number(6),hisal number(6));


Table created.

SQL> desc salgrade


Name Null? Type
----------------------------------------- --------
GRADE NUMBER(5)
LOSAL NUMBER(6)
HISAL NUMBER(6)

SQL> insert into salgrade values(1,700,1200);


1 row created.
SQL> insert into salgrade values(2,1201,1400);
1 row created.
SQL> insert into salgrade values(3,1401,2000);
1 row created.
SQL> insert into salgrade values(4,2001,3000);
1 row created.
SQL> insert into salgrade values(5,3001,9999);
1 row created.

SQL> select * from salgrade;


GRADE LOSAL HISAL
---------- ---------- ----------
1 700 1200
2 1201 1400
3 1401 2000
4 2001 3000
5 3001 9999

SQL> create table emp (empno number(5) primary key,ename varchar2(10) not
null,job varchar2(10),mgr number(4),hiredate date,sal number(7,2)
check(sal>=500 and sal<=10000),comm number(7,2),deptno number(2), foreign
key(deptno) references dept);

Table created.

SQL> insert into


emp(empno,ename,job,mgr,hiredate,sal,deptno)values(7369,'smith','clerk',7902
,'17-dec-80',800,20);
1 row created.

SQL> insert into


emp(empno,ename,job,mgr,hiredate,sal,comm,deptno)values(7499,'allen','salesm
an',7698,'20-feb-81',1600,300,30);
1 row created.

SQL> insert into


emp(empno,ename,job,mgr,hiredate,sal,comm,deptno)values(7521,'ward','salesma
n',7698,'22-feb-81',1250,500,30);
1 row created.

SQL> insert into


emp(empno,ename,job,mgr,hiredate,sal,deptno)values(7566,'jones','manager',78
39,'2-apr-81',2975,20);
1 row created.

SQL> insert into


emp(empno,ename,job,mgr,hiredate,sal,comm,deptno)values(7654,'martin','sales
man',7698,'28-sep-81',1250,1400,30);
1 row created.

SQL> insert into


emp(empno,ename,job,mgr,hiredate,sal,deptno)values(7698,'blake','manager',78
39,'1-may-81',2850,30);
1 row created.

SQL> insert into


emp(empno,ename,job,mgr,hiredate,sal,deptno)values(7782,'clark','manager',78
39,'9-jun-81',2450,10);
1 row created.

SQL> insert into


emp(empno,ename,job,mgr,hiredate,sal,deptno)values(7788,'scott','analyst',75
66,'19-apr-87',3000,20);
1 row created.
SQL> insert into
emp(empno,ename,job,hiredate,sal,deptno)values(7839,'king','president','17-
nov-81',5000,10);
1 row created.

SQL> insert into


emp(empno,ename,job,mgr,hiredate,sal,comm,deptno)values(7844,'turner','sales
man',7698,'8-sep-81',1000,0,30);
1 row created.

SQL> insert into


emp(empno,ename,job,mgr,hiredate,sal,deptno)values(7876,'adems','clerk',7788
,'23-may-87',1100,20);
1 row created.

SQL> insert into


emp(empno,ename,job,mgr,hiredate,sal,deptno)values(7900,'james','clerk',7698
,'3-dec-81',950,30);
1 row created.

SQL> insert into


emp(empno,ename,job,mgr,hiredate,sal,deptno)values(7902,'ford','analyst',756
6,'3-dec-81',3000,20);
1 row created.

SQL> insert into


emp(empno,ename,job,mgr,hiredate,sal,deptno)values(7934,'miller','clerk',778
2,'23-jan-82',1300,10);
1 row created.

SQL> select * from emp;


EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
---------- ---------- ----------
7369 smith clerk 7902 17-DEC-80 800 20
7499 allen salesman 7698 20-FEB-81 1600 300 30
7521 ward salesman 7698 22-FEB-81 1250 500 30
7566 jones manager 7839 02-APR-81 2975 20
7654 martin salesman 7698 28-SEP-81 1250 1400 30
7698 blake manager 7839 01-MAY-81 2850 30
7782 clark manager 7839 09-JUN-81 2450 10
7788 scott analyst 7566 19-APR-87 3000 20
7839 king president 17-NOV-81 5000 10
7844 turner salesman 7698 08-SEP-81 1000 0 30
7876 adems clerk 7788 23-MAY-87 1100 20
7900 james clerk 7698 03-DEC-81 950 30
7902 ford analyst 7566 03-DEC-81 3000 20
7934 miller clerk 7782 23-JAN-82 1300 10

14 rows selected.
1. Queries to facilitate acquaintance of Built-In Functions, String Functions, Numeric Functions,
Date Functions and Conversion Functions.

SQL> select ABS(-65) from dual;


ABS(-65)
----------
65
SQL> select CEIL(SAL) "CEIL(88.9) from emp
where sal BETWEEN 3000 AND 5000;

CEIL(88.9)
----------
3000
5000
3000
SQL> select FLOOR(SAL),CEIL(88.9) from emp
where sal BETWEEN 3000 AND 5000;

FLOOR(SAL) CEIL(88.9)
---------- ----------
3000 89
5000 89
3000 89

SQL> select MOD(200,300) from dual;

MOD(200,300)
------------
200

SQL> select sal,POWER(sal,2) from emp where deptno=10;

SAL POWER(SAL,2)
---------- ------------
2450 6002500
5000 25000000
1300 1690000

SQL> select comm-sal,SIGN(comm-sal) from emp where deptno=30;

COMM-SAL SIGN(COMM-SAL)
---------- --------------
-1300 -1
-750 -1
150 1

-1500 -1
SQL> select sal,SQRT(sal) from emp where deptno=10;
SAL SQRT(SAL)
---------- ----------
2450 49.4974747
5000 70.7106781
1300 36.0555128
SQL> select TRUNC(90.723,1),TRUNC(90.723,-1),TRUNC(90.723) from dual;

TRUNC(90.723,1) TRUNC(90.723,-1) TRUNC(90.723)


--------------- ---------------- -------------
90.7 90 90

SQL> select sal,TRUNC(SQRT(sal),2) from emp where deptno=10;

SAL TRUNC(SQRT(SAL),2)
---------- ------------------
2450 49.49
5000 70.71
1300 36.05

SQL> select ROUND(90.723,1),ROUND(90.723,-1),ROUND(90.723) from dual;

ROUND(90.723,1) ROUND(90.723,-1) ROUND(90.723)


--------------- ---------------- -------------
90.7 90 91

SQL> select sal,ROUND(SQRT(sal),2) from emp where deptno=10;

SAL ROUND(SQRT(SAL),2)
---------- ------------------
2450 49.5
5000 70.71
1300 36.06

SQL> select EXP(4) from dual;

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

SQL> select CHR(37) a,CHR(100) b,CHR(101) c from dual;

A B C
- - -
% d e

SQL> select CONCAT('Alphabet','soup') "Dinner" from dual;


Dinner
------------
Alphabetsoup

SQL> select INITCAP(dname) from dept;


INITCAP(DNAME)
--------------------
accounting
sales
research
operations
SQL> select LOWER(dname),LOWER('XYZ') from dept;
LOWER(DNAME) LOW
-------------------- ---
accounting xyz
sales xyz
research xyz
operations xyz

SQL> select UPPER(dname),UPPER('abc') from dept;

UPPER(DNAME) UPP
-------------------- ---
accounting abc
sales abc
research abc
operations abc

SQL> select LPAD(dname,15,'$'),LPAD(dname,15,'') from dept;

LPAD(DNAME,15,'$')
------------------------------------------------------------
LPAD(DNAME,15,'')
------------------------------------------------------------
$$$$$accounting
$$$$$$$$$$sales
$$$$$$$research

LPAD(DNAME,15,'$')
------------------------------------------------------------
LPAD(DNAME,15,'')
------------------------------------------------------------
$$$$$operations

SQL> select RPAD(dname,15,'$'),RPAD(dname,15,'') from dept;

RPAD(DNAME,15,'$')
------------------------------------------------------------
RPAD(DNAME,15,'')
------------------------------------------------------------
accounting$$$$$
sales$$$$$$$$$$
research$$$$$$$
RPAD(DNAME,15,'$')
------------------------------------------------------------
RPAD(DNAME,15,'')
------------------------------------------------------------
operations$$$$$

SQL> select dname,LTRIM(dname),LTRIM(dname,'R') from dept;


DNAME LTRIM(DNAME) LTRIM(DNAME,'R')
-------------------- -------------------- --------------------
accounting accounting accounting
sales sales sales
research research research
operations operations operations
SQL> select dname,RTRIM(dname),RTRIM(dname,'s') from dept;

DNAME RTRIM(DNAME) RTRIM(DNAME,'S')


-------------------- -------------------- --------------------
accounting accounting accounting
sales sales sale
research research research
operations operations operation

SQL> select REPLACE('This and That','Th','B')"First" from dual;

First
-----------
Bis and Bat

SQL> select REPLACE('This and That','Th')"Second" from dual;

Second
---------
is and at

SQL> select dname,SUBSTR(dname,2,4),SUBSTR(dname,4) from dept;

DNAME SUBSTR(DNAME,2,4
-------------------- ----------------
SUBSTR(DNAME,4)
--------------------------------------------------------------------
accounting ccouounting
sales aleses
research eseaearch

DNAME SUBSTR(DNAME,2,4
-------------------- ----------------
SUBSTR(DNAME,4)
--------------------------------------------------------------------
operations perarations

SQL> select TRANSLATE('abcdefghij','abcdef','123456') from dual;

TRANSLATE(
----------
123456ghij

SQL> select dname,LTRIM(dname),LTRIM(dname,'s') from dept;

DNAME LTRIM(DNAME) LTRIM(DNAME,'S')


-------------------- -------------------- --------------------
accounting accounting accounting
sales sales ales
research research research
operations operations operations

SQL> select dname,LTRIM(dname),LTRIM(dname,'r') from dept;


DNAME LTRIM(DNAME) LTRIM(DNAME,'R')
-------------------- -------------------- --------------------
accounting accounting accounting
sales sales sales
research research esearch
operations operations operations

SQL> select TRANSLATE('abcdefghij','abcdefghij','123456') from dual;


TRANSL
------
123456

SQL> select ASCII('') from dual;


ASCII('')
----------

SQL> select ASCII(' ') from dual;


ASCII('')
----------
32

SQL> select ASCII('a') from dual;


ASCII('A')
----------
97

SQL> select dname,INSTR(dname,'e') from dept;

DNAME INSTR(DNAME,'E')
-------------------- ----------------
accounting 0
sales 4
research 2
operations 3

SQL> select dname,LENGTH(dname) from dept;

DNAME LENGTH(DNAME)
-------------------- -------------
accounting 10
sales 5
research 8
operations 10

SQL> select UPPER(ename),LOWER(ename),INITCAP(ename),LENGTH(ename)


from emp;

UPPER(ENAM LOWER(ENAM INITCAP(EN LENGTH(ENAME)


---------- ---------- ---------- -------------
SMITH smith Smith 5
ALLEN allen Allen 5
WARD ward Ward 4
JONES jones Jones 5
MARTIN martin Martin 6
BLAKE blake Blake 5
CLARK clark Clark 5
SCOTT scott Scott 5
KING king King 4
TURNER turner Turner 6
ADAMS adams Adams 5

UPPER(ENAM LOWER(ENAM INITCAP(EN LENGTH(ENAME)


---------- ---------- ---------- -------------
JAMES james James 5
FORD ford Ford 4
MILLER miller Miller 6

14 rows selected.

SQL> select
ename,INSTR(ename,'a'),SUBSTR(job,1,3),LPAD(ename,10,'.'),RPAD(ename,10,'.')
2 from emp;

ENAME INSTR(ENAME,'A') SUBSTR(JOB,1


---------- ---------------- ------------
LPAD(ENAME,10,'.')
----------------------------------------
RPAD(ENAME,10,'.')
----------------------------------------
smith 0 cle
.....smith
smith.....

allen 1 sal
.....allen
allen.....

ENAME INSTR(ENAME,'A') SUBSTR(JOB,1


---------- ---------------- ------------
LPAD(ENAME,10,'.')
----------------------------------------
RPAD(ENAME,10,'.')
----------------------------------------

ward 2 sal
......ward
ward......

jones 0 man
.....jones

ENAME INSTR(ENAME,'A') SUBSTR(JOB,1


---------- ---------------- ------------
LPAD(ENAME,10,'.')
----------------------------------------
RPAD(ENAME,10,'.')
----------------------------------------
jones.....

martin 2 sal
....martin
martin....

blake 3 man

ENAME INSTR(ENAME,'A') SUBSTR(JOB,1


---------- ---------------- ------------
LPAD(ENAME,10,'.')
----------------------------------------
RPAD(ENAME,10,'.')
----------------------------------------
.....blake
blake.....

clark 3 man
.....clark
clark.....

ENAME INSTR(ENAME,'A') SUBSTR(JOB,1


---------- ---------------- ------------
LPAD(ENAME,10,'.')
----------------------------------------
RPAD(ENAME,10,'.')
----------------------------------------
scott 0 ana
.....scott
scott.....

king 0 pre
......king
king......

ENAME INSTR(ENAME,'A') SUBSTR(JOB,1


---------- ---------------- ------------
LPAD(ENAME,10,'.')
----------------------------------------
RPAD(ENAME,10,'.')
----------------------------------------

turner 0 sal
....turner
turner....

adams 1 cle
.....adams

ENAME INSTR(ENAME,'A') SUBSTR(JOB,1


---------- ---------------- ------------
LPAD(ENAME,10,'.')
----------------------------------------
RPAD(ENAME,10,'.')
----------------------------------------
adams.....

james 2 cle
.....james
james.....

ford 0 ana

ENAME INSTR(ENAME,'A') SUBSTR(JOB,1


---------- ---------------- ------------
LPAD(ENAME,10,'.')
----------------------------------------
RPAD(ENAME,10,'.')
----------------------------------------
......ford
ford......

miller 0 cle
....miller
miller....

14 rows selected.

SQL> select SYSDATE from dual;

SYSDATE
------------------
13-AUG-15

SQL> select hireddate,ADD_MONTHS(hireddate,4),ADD_MONTHS(hireddate,-4)


2 from emp where deptno=10;

HIREDDATE ADD_MONTHS(HIREDDA ADD_MONTHS(HIREDDA


------------------ ------------------ ------------------
09-JUN-81 09-OCT-81 09-FEB-81
17-NOV-81 17-MAR-82 17-JUL-81
23-JAN-82 23-MAY-82 23-SEP-81

SQL> select ROUND(TO_DATE('12-apr-71'),'MM') "Nearest month"


from dual;
Nearest month
------------------
01-APR-71

SQL> select MONTHS_BETWEEN('05-jan-98','05-jan-98'),MONTHS_BETWEEN('05-mar-


98','05-jan-98')
2 from dual;
MONTHS_BETWEEN('05-JAN-98','05-JAN-98') MONTHS_BETWEEN('05-MAR-98','05-JAN-
98')
---------------------------------------
---------------------------------------
0 2

SQL> select SYSDATE,LAST_DAY(SYSDATE)


2 from dual;
SYSDATE LAST_DAY(SYSDATE)
------------------ ------------------
13-AUG-15 31-AUG-15

SQL> select MONTHS_BETWEEN('05-jan-98','05-mar-98'),MONTHS_BETWEEN('05-mar-


98','05-jan-98'from dual;

MONTHS_BETWEEN('05-JAN-98','05-MAR-98') MONTHS_BETWEEN('05-MAR-98','05-JAN-
98')
--------------------------------------- ----------------------------------
-2 2

SQL> select SYSDATE,NEXT_DAY(SYSDATE,'WEDNESDAY') from dual;

SYSDATE NEXT_DAY(SYSDATE,'
------------------ ------------------
13-AUG-15 19-AUG-15

SQL> select SYSDATE,TO_CHAR(SYSDATE,'DAY') from dual;

SYSDATE TO_CHAR(SYSDATE,'DAY')
------------------ ------------------------------------
13-AUG-15 THURSDAY

SQL> select TO_CHAR(TO_DATE('20-mar-98'),'RM') from dual;


TO_C
----
III

SQL> select GREATEST(10,'7',-1) from dual;

GREATEST(10,'7',-1)
-------------------
10

SQL> select LEAST('abcd','ABCD','a','XYZ') "Least" from dual;

Leas
----
ABCD

SQL> select ename,sal,comm,sal+comm,gross,sal+NULL(comm,0) "New Gross"

SQL> select dname,TRANSLATE(dname,'e','1') from dept;


DNAME
--------------------
TRANSLATE(DNAME,'E','1')
--------------------------------------------------------------------------
accounting
accounting
sales
sal1s
research
r1s1arch
DNAME
--------------------
TRANSLATE(DNAME,'E','1')
--------------------------------------------------------------------------
operations
op1rations

SQL> select ename,TO_CHAR(hireddate,'DD/MM/YY') as hireddate


2 from emp
3 where deptno=20;

ENAME HIREDDAT
---------- --------
smith 17/12/80
jones 02/04/81
scott 19/04/87
adams 23/05/87
ford 03/12/81

SQL> select eno,ename,job,TO_CHAR(sal,'$9.999') as sal


2 from emp;

ENO ENAME JOB SAL


---------- ---------- ---------- -------
7369 smith clerk #######
7499 allen salesman #######
7521 ward salesman #######
7566 jones manager #######
7654 martin salesman #######
7698 blake manager #######
7782 clark manager #######
7788 scott analyst #######
7839 king president #######
7844 turner salesman #######
7876 adams clerk #######

ENO ENAME JOB SAL


---------- ---------- ---------- -------
7900 james clerk #######
7902 ford analyst #######
7984 miller clerk #######
14 rows selected.
SQL> select eno,ename,job,TO_CHAR(sal,'$9999') as salary from emp;

ENO ENAME JOB SALARY


---------- ---------- ---------- ------
7369 smith clerk $800
7499 allen salesman $1600
7521 ward salesman $1250
7566 jones manager $2975
7654 martin salesman $1250
7698 blake manager $2850
7782 clark manager $2450
7788 scott analyst $3000
7839 king president $5000
7844 turner salesman $1500
7876 adams clerk $1100
ENO ENAME JOB SALARY
---------- ---------- ---------- ------
7900 james clerk $950
7902 ford analyst $3000
7984 miller clerk $1300

14 rows selected.

SQL> select TO_CHAR(hireddate,'YY') as YY,count(*)


2 from emp
3 group by TO_CHAR(hireddate,'YY');

YY COUNT(*)
-- ----------
87 2
81 10
82 1
80 1

SQL> select ename,TO_CHAR(hireddate,'MON YY') as hireddate


2 from emp
3 where TO_CHAR(hireddate) BETWEEN TO_DATE('01-apr-81')
4 and TO_DATE('30-apr-82');

ENAME HIREDDATE
---------- ---------------
jones APR 81
martin SEP 81
blake MAY 81
clark JUN 81
king NOV 81
turner SEP 81
james DEC 81
ford DEC 81
miller JAN 82

9 rows selected.
SQL> select ename,sal+TO_NUMBER('100.00') as salary
2 from emp;

ENAME SALARY
---------- ----------
smith 900
allen 1700
ward 1350
jones 3075
martin 1350
blake 2950
clark 2550
scott 3100
king 5100
turner 1600
adams 1200

ENAME SALARY
---------- ----------
james 1050
ford 3100
miller 1400

14 rows selected.

SQL> select 'Department number'||


2 deptno||
3 'with name'||
4 INITCAP(dname)||
5 'is situated in'||
6 INITCAP(loc)
7 as concatenatedstring
8 from dept;

CONCATENATEDSTRING
----------------------------------------------------------------------------
----
Department number10with nameAccountingis situated inNewyork
Department number20with nameSalesis situated inChicago
Department number30with nameResearchis situated inDallas
Department number40with nameOperationsis situated inBoston

SQL> select LPAD(ename,9,'*')


2 from emp;

LPAD(ENAME,9,'*')
------------------------------------
****smith
****allen
*****ward
****jones
***martin
****blake
****clark
****scott
*****king
***turner
****adams

LPAD(ENAME,9,'*')
------------------------------------
****james
*****ford
***miller
14 rows selected.

SQL> select RPAD(ename,9,'*')


2 from emp;

RPAD(ENAME,9,'*')
------------------------------------
smith****
allen****
ward*****
jones****
martin***
blake****
clark****
scott****
king*****
turner***
adams****

RPAD(ENAME,9,'*')
------------------------------------
james****
ford*****
miller***
14 rows selected.

SQL> select LTRIM(ename,'s') from emp where deptno=20;

LTRIM(ENAM
----------
mith
jones
cott
adams
ford

SQL> select RTRIM(ename,'s') from emp where deptno=20;


RTRIM(ENAM
----------
smith
jone
scott
adam
ford
SQL> select ename,UPPER(ename),LOWER(ename),INITCAP(ename)from emp
2 where deptno=10;

ENAME UPPER(ENAM LOWER(ENAM INITCAP(EN


---------- ---------- ---------- ----------
clark CLARK clark Clark
king KING king King
miller MILLER miller Miller

SQL> select ename,LENGTH(ename)


2 from emp
3 where deptno=30
4 order by LENGTH(ename);

ENAME LENGTH(ENAME)
---------- -------------
ward 4
allen 5
james 5
blake 5
turner 6
martin 6

6 rows selected.

SQL> select DISTINCT(SUBSTR(job,1,4)) as job


2 from emp;

JOB
----------------
anal
cler
pres
sale
mana

SQL> select ename,INSTR(ename,'s')


2 from emp
3 where deptno=20;

ENAME INSTR(ENAME,'S')
---------- ----------------
smith 1
jones 5
scott 1
adams 5
ford 0

SQL> select NEXT_DAY(hireddate,'SUN') as holiday


2 from emp;

HOLIDAY
------------------
21-DEC-80
22-FEB-81
01-MAR-81
05-APR-81
04-OCT-81
03-MAY-81
14-JUN-81
26-APR-87
22-NOV-81
13-SEP-81
24-MAY-87

HOLIDAY
------------------
06-DEC-81
06-DEC-81
24-JAN-82

14 rows selected.

SQL> select hireddate,ADD_MONTHS(hireddate,12) as REVIEWDATE


2 from emp
3 where deptno=20;

HIREDDATE REVIEWDATE
------------------ ------------------
17-DEC-80 17-DEC-81
02-APR-81 02-APR-82
19-APR-87 19-APR-88
23-MAY-87 23-MAY-88
03-DEC-81 03-DEC-82

SQL> select hireddate,LAST_DAY(hireddate) as LASTDAY


2 from emp
3 where deptno=10;

HIREDDATE LASTDAY
------------------ ------------------
09-JUN-81 30-JUN-81
17-NOV-81 30-NOV-81
23-JAN-82 31-JAN-82

SQL> select LEAST(9,3,56,89,23,1,0,-2,12,34,7,22) as LOWEST


2 from dual;

LOWEST
----------
-2

SQL> select GREATEST(9,3,56,89,23,1,0,-2,12,34,7,22) as HIGHEST from dual;

HIGHEST
----------
89
SQL> select TRUNC(567,23165613)
2 from dual;

TRUNC(567,23165613)
-------------------
567

SQL> select TRUNC(567.231651,3)


2 from dual;

TRUNC(567.231651,3)
-------------------
567.231

2. Queries using operators in SQL

Arithmetic operators:

SQL> select ename,sal,sal+500 from emp;

ENAME SAL SAL+500


---------- ---------- ----------
smith 800 1300
allen 1600 2100
ward 1250 1750
jones 2975 3475
martin 1250 1750
blake 2850 3350
clark 2450 2950
scott 3000 3500
king 5000 5500
turner 10000 10500
adems 1100 1600
james 950 1450
ford 3000 3500
miller 1300 1800

14 rows selected.

SQL> select ename,sal,sal-500 from emp;

ENAME SAL SAL-500


---------- ---------- ----------
smith 800 300
allen 1600 1100
ward 1250 750
jones 2975 2475
martin 1250 750
blake 2850 2350
clark 2450 1950
scott 3000 2500
king 5000 4500
turner 10000 9500
adems 1100 600
james 950 450
ford 3000 2500
miller 1300 800

14 rows selected.

SQL> select ename,sal,sal*500 from emp;

ENAME SAL SAL*500


---------- ---------- ----------
smith 800 400000
allen 1600 800000
ward 1250 625000
jones 2975 1487500
martin 1250 625000
blake 2850 1425000
clark 2450 1225000
scott 3000 1500000
king 5000 2500000
turner 10000 5000000
adems 1100 550000
james 950 475000
ford 3000 1500000
miller 1300 650000

14 rows selected.

SQL> select ename,sal,sal/500 from emp;

ENAME SAL SAL/500


---------- ---------- ----------
smith 800 1.6
allen 1600 3.2
ward 1250 2.5
jones 2975 5.95
martin 1250 2.5
blake 2850 5.7
clark 2450 4.9
scott 3000 6
king 5000 10
turner 10000 20
adems 1100 2.2
james 950 1.9
ford 3000 6
miller 1300 2.6

14 rows selected.

Concatenation operator:

SQL> SELECT 'Name is ' || ename


2 FROM emp;

'NAMEIS'||ENAME
------------------
Name is smith
Name is allen
Name is ward
Name is jones
Name is martin
Name is blake
Name is clark
Name is scott
Name is king
Name is turner
Name is adems
Name is james
Name is ford
Name is miller

14 rows selected.

Comparison operators:

SQL> select *from emp where sal=3000;

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


---------- ---------- ---------- ---------- -------------- ----- ------
7788 scott analyst 7566 19-APR-87 3000 20
7902 ford analyst 7566 03-DEC-81 3000 20

SQL> select *from emp where sal>3000;

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


---------- ---------- ---------- ---------- --------- ---------- ---- ----- ------
7839 king president 17-NOV-81 5000 10
7844 turner salesman 7698 08-SEP-81 10000 0 30

SQL> select *from emp where sal<3000;

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


---------- ---------- ---------- ---------- --------- ------ ---- ----- ------
7369 smith clerk 7902 17-DEC-80 800 20
7499 allen salesman 7698 20-FEB-81 1600 300 30
7521 ward salesman 7698 22-FEB-81 1250 500 30
7566 jones manager 7839 02-APR-81 2975 20
7654 martin salesman 7698 28-SEP-81 1250 1400 30
7698 blake manager 7839 01-MAY-81 2850 30
7782 clark manager 7839 09-JAN-81 2450 10
7876 adems clerk 7788 23-MAY-87 1100 20
7900 james clerk 7698 03-DEC-81 950 30
7934 miller clerk 7782 23-JAN-82 1300 10

10 rows selected.

SQL> select *from emp where sal<=3000;

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


---------- ---------- ---- ------ ---- ---- --------- ---------- ----- ------
7369 smith clerk 7902 17-DEC-80 800 20
7499 allen salesman 7698 20-FEB-81 1600 300 30
7521 ward salesman 7698 22-FEB-81 1250 500 30
7566 jones manager 7839 02-APR-81 2975 20
7654 martin salesman 7698 28-SEP-81 1250 1400 30
7698 blake manager 7839 01-MAY-81 2850 30
7782 clark manager 7839 09-JAN-81 2450 10
7788 scott analyst 7566 19-APR-87 3000 20
7876 adems clerk 7788 23-MAY-87 1100 20
7900 james clerk 7698 03-DEC-81 950 30
7902 ford analyst 7566 03-DEC-81 3000 20
7934 miller clerk 7782 23-JAN-82 1300 10

12 rows selected.

SQL> select *from emp where sal>=3000;

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


---------- ---------- ---------- ---------- --------- ---------- ----- ------
7788 scott analyst 7566 19-APR-87 3000 20
7839 king president 17-NOV-81 5000 10
7844 turner salesman 7698 08-SEP-81 10000 0 30
7902 ford analyst 7566 03-DEC-81 3000 20

SQL> select *from emp where sal!=3000;(we can use <>or ^= also)

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


---------- ---------- ---- ------ - --------- --------- ---------- ----- ------
7369 smith clerk 7902 17-DEC-80 800 20
7499 allen salesman 7698 20-FEB-81 1600 300 30
7521 ward salesman 7698 22-FEB-81 1250 500 30
7566 jones manager 7839 02-APR-81 2975 20
7654 martin salesman 7698 28-SEP-81 1250 1400 30
7698 blake manager 7839 01-MAY-81 2850 30
7782 clark manager 7839 09-JAN-81 2450 10
7839 king president 17-NOV-81 5000 10
7844 turner salesman 7698 08-SEP-81 10000 0 30
7876 adems clerk 7788 23-MAY-87 1100 20
7900 james clerk 7698 03-DEC-81 950 30
7934 miller clerk 7782 23-JAN-82 1300 10

12 rows selected.

SQL> SELECT * FROM emp


2 WHERE job IN
3 ('clerk','analyst');
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
---------- ---------- ---------- ---------- --------- ---------- ----- ------ -------
7369 smith clerk 7902 17-DEC-80 800 20
7788 scott analyst 7566 19-APR-87 3000 20
7876 adems clerk 7788 23-MAY-87 1100 20
7900 james clerk 7698 03-DEC-81 950 30
7902 ford analyst 7566 03-DEC-81 3000 20
7934 miller clerk 7782 23-JAN-82 1300 10

6 rows selected.

SQL> select *from emp where job not in ('clerk','analyst');

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


---------- ---------- ---------- ---------- --------- ---------- ----- ------ --------
7499 allen salesman 7698 20-FEB-81 1600 300 30
7521 ward salesman 7698 22-FEB-81 1250 500 30
7566 jones manager 7839 02-APR-81 2975 20
7654 martin salesman 7698 28-SEP-81 1250 1400 30
7698 blake manager 7839 01-MAY-81 2850 30
7782 clark manager 7839 09-JAN-81 2450 10
7839 king president 17-NOV-81 5000 10
7844 turner salesman 7698 08-SEP-81 10000 0 30

8 rows selected.

SQL> select empno,ename,job,deptno from emp e where exists(select empno


from emp where emp.mgr=e.empno);
EMPNO ENAME JOB DEPTNO
---------- --------- --------- ----------
7698 blake manager 30
7839 king president 10
7566 jones manager 20
7788 scott analyst 20
7782 clark manager 10
7902 ford analyst 20
6 rows selected.

select ename,job from emp e where not exists(select mgr from emp where
mgr=e.empno);
ENAME JOB
--------- ---------
turner salesman
ward salesman
martin salesman
allen salesman
miller clerk
smith clerk
adems clerk
james clerk
8 rows selected.

SQL> select ename from emp where sal =any(select sal from emp where deptno=20);

ENAME
----------
smith
jones
ford
scott
adems

SQL> select ename from emp where sal <any(select sal from emp where deptno=20);

ENAME
----------
smith
james
adems
ward
martin
miller
allen
clark
blake
jones

10 rows selected.

SQL> select ename from emp where sal >any(select sal from emp where deptno=20);

ENAME
----------
turner
king
ford
scott
jones
blake
clark
allen
miller
martin
ward
adems
james

13 rows selected.

SQL> select ename from emp where sal =all(select sal from emp where deptno=30)

no rows selected

SQL> select ename from emp where sal <all(select sal from emp where deptno=30)

ENAME
----------
smith

SQL> select ename from emp where sal >all(select sal from emp where deptno=20)

ENAME
----------
king
turner
SQL> select e.ename from emp e,dept d
where e.deptno=d.deptno and d.loc='dallas'
union
select e.ename from emp e,dept d
where e.deptno=d.deptno and d.loc='newyork';
ENAME
---------
clark
king
miller

SQL> select e.deptno from emp e INTERSECT select d.deptno from dept d;
DEPTNO
----------
10
20
30
SQL> select deptno from dept minus select deptno from emp;

DEPTNO

SQL> select ename,sal from emp;


ENAME SAL
--------- ----------
allen 1600
ward 1250
jones 2975
martin 1250
blake 2850
clark 2450
scott 3000
king 5000
turner 10000
adems 1100
ford 3000

ENAME SAL
--------- ----------
miller 1300
smith 800
james 950
14 rows selected.

SQL> select ename,empno,sal from emp where comm is null;

ENAME EMPNO SAL


---------- ---------- ----------
smith 7369 800
jones 7566 2975
blake 7698 2850
clark 7782 2450
scott 7788 3000
king 7839 5000
adems 7876 1100
james 7900 950
ford 7902 3000
miller 7934 1300

10 rows selected.

SQL> select ename,empno,sal from emp where comm is not null;

ENAME EMPNO SAL


---------- ---------- ----------
allen 7499 1600
ward 7521 1250
martin 7654 1250
turner 7844 10000

SQL> select ename,empno,sal from emp where sal between 1000 and 3000;

ENAME EMPNO SAL


---------- - --------- -- --------
allen 7499 1600
ward 7521 1250
jones 7566 2975
martin 7654 1250
blake 7698 2850
clark 7782 2450
scott 7788 3000
adems 7876 1100
ford 7902 3000
miller 7934 1300

10 rows selected.

SQL> select ename,empno,sal from emp where sal not between 1000 and 3000;

ENAME EMPNO SAL


---------- ---------- ----------
smith 7369 800
king 7839 5000
turner 7844 10000
james 7900 950

SQL> select ename, sal from emp where ename like's%';


ENAME SAL
---------- ----------
smith 800
scott 3000

SQL> select ename, sal from emp where ename not like's%';

ENAME SAL
---------- ----------
allen 1600
ward 1250
jones 2975
martin 1250
blake 2850
clark 2450
king 5000
turner 10000
adems 1100
james 950
ford 3000
miller 1300

12 rows selected.

SQL> select ename, sal from emp where ename like '%s';

ENAME SAL
---------- ----------
jones 2975
adems 1100
james 950

SQL> select ename, sal from emp where ename like 'smit_';

ENAME SAL
---------- ----------
smith 800

SQL> select ename, sal from emp where ename like '__nes';

ENAME SAL
---------- ----------
jones 2975
SQL> select ename,sal from emp where deptno=20 and job='clerk';

ENAME SAL
---------- ----------
smith 800
adems 1100

SQL> select ename,sal from emp where deptno=20 or job='clerk';

ENAME SAL
---------- ----------
smith 800
jones 2975
scott 3000
adems 1100
james 950
ford 3000
miller 1300

7 rows selected.

SQL> select ename,job,sal from emp where not(job='clerk');

ENAME JOB SAL


---------- ---------- ----------
allen salesman 1600
ward salesman 1250
jones manager 2975
martin salesman 1250
blake manager 2850
clark manager 2450
scott analyst 3000
king president 5000
turner salesman 10000
ford analyst 3000

10 ows selected.

3. Queries to Retrieve and Change Data: Select, Insert, Delete, and Update

SQL> create table college(cid varchar2(4) primary key,cname varchar2(10) not nul
l,cplace varchar2(10));

Table created.

SQL> insert into college values('c1','cone','cplace1');


1 row created.

SQL> insert into college values('c2','ctwo','cplace2');

1 row created.

SQL> insert into college values('c3','cthr','cplace3');

1 row created.

SQL> commit;

Commit complete.

SQL> select *from college;

CID CNAME CPLACE


---- ---------- ----------
c1 cone cplace1
c2 ctwo cplace2
c3 cthr cplace3

SQL> create table student(sid varchar2(4) primary key,sname varchar2(10) not nul
l,cid varchar2(10) references college(cid));

Table created.

SQL> insert into student values('s1','sone','c1');

1 row created.

SQL> insert into student values('s2','stwo','c1');

1 row created.

SQL> insert into student values('s3','sthr','c3');

1 row created.

SQL> insert into student values('s4','sfour','c2');

1 row created.

SQL> commit;
Commit complete.

SQL> select *from student;

SID SNAME CID


---- ---------- ----------
s1 sone c1
s2 stwo c1
s3 sthr c3
s4 sfour c2

SQL> delete from student where sid='s4';

1 row deleted.

SQL> select *from student;

SID SNAME CID


---- ---------- ----------
s1 sone c1
s2 stwo c1
s3 sthr c3

SQL> update student set sname='new sone' where sid='s1';

1 row updated.

SQL> select *from student;

SID SNAME CID


---- ---------- ----------
s1 new sone c1
s2 stwo c1
s3 sthr c3

SQL> update student set sname='new sthr' where sid='s3';

1 row updated.

SQL> select *from student;

SID SNAME CID


---- ---------- ----------
s1 new sone c1
s2 stwo c1
s3 new sthr c3

SQL> alter table student add marks number(4);

Table altered.

SQL> desc student;


Name Null? Type
----------------------------------------------------- -------- ---------------
--------------------
SID NOT NULL VARCHAR2(4)
SNAME NOT NULL VARCHAR2(10)
CID VARCHAR2(10)
MARKS NUMBER(4)

SQL> alter table student modify sname varchar2(20);

Table altered.

SQL> desc student;


Name Null? Type
----------------------------------------------------- -------- ---------------
--------------------
SID NOT NULL VARCHAR2(4)
SNAME NOT NULL VARCHAR2(20)
CID VARCHAR2(10)
MARKS NUMBER(4)

SQL> desc student;


Name Null? Type
----------------------------------------------------- -------- ----------------
--------------------
SID NOT NULL VARCHAR2(4)
SNAME NOT NULL VARCHAR2(20)
CID VARCHAR2(10)
MARKS NUMBER(4)

SQL> alter table student drop column marks;

Table altered.

SQL> desc student;


Name Null? Type
----------------------------------------------------- -------- ----------------
--------------------
SID NOT NULL VARCHAR2(4)
SNAME NOT NULL VARCHAR2(20)
CID VARCHAR2(10)

SQL> alter table college add constraint c1 unique(cplace);

Table altered.

SQL> select *from college;

CID CNAME CPLACE


---- ---------- ----------
c1 cone cplace1
c2 ctwo cplace2
c3 cthr cplace3

SQL> insert into college values('c4','cfour','cplace3');


insert into college values('c4','cfour','cplace3')
*
ERROR at line 1:
ORA-00001: unique constraint (SCOTT.C1) violated

4)Queries using Group By, Order By, and Having Clauses

SQL> select count(*) from emp;


COUNT(*)
----------
14
SQL> select count(distinct job) from emp;
COUNT(DISTINCTJOB)
------------------
5
SQL> select sum(sal) from emp;
SUM(SAL)
----------
37525
SQL> select max(sal) from emp where job='salesman';
MAX(SAL)
----------
10000
SQL> select min(sal) from emp;
MIN(SAL)
----------
800
SQL> select avg(sal),count(*) from emp where deptno=20;
AVG(SAL) COUNT(*)
---------- ----------
2175 5
SQL> select deptno,count(*) from emp group by deptno;
DEPTNO COUNT(*)
---------- ----------
30 6
20 5
10 3

SQL> select deptno,sum(sal) from emp emp group by deptno;


DEPTNO SUM(SAL)
---------- ----------
30 17900
20 10875
10 8750

SQL> select job,count(*) from emp group by job order by count(*) desc;
JOB COUNT(*)
--------- ----------
salesman 4
clerk 4
manager 3
analyst 2
president 1

SQL> select job,sum(sal),avg(sal),max(sal),min(sal) from emp group by job;

JOB SUM(SAL) AVG(SAL) MAX(SAL) MIN(SAL)


--------- ---------- ---------- ---------- ----------
salesman 14100 3525 10000 1250
president 5000 5000 5000 5000
clerk 4150 1037.5 1300 800
manager 8275 2758.33333 2975 2450
analyst 6000 3000 3000 3000
SQL> select job,avg(sal) from emp where job!='manager' group by job;
JOB AVG(SAL)
--------- ----------
salesman 3525
president 5000
clerk 1037.5
analyst 3000

SQL> select job,sum(sal),avg(sal),max(sal),min(sal) from emp where deptno=20


group by job;
JOB SUM(SAL) AVG(SAL) MAX(SAL) MIN(SAL)
--------- ---------- ---------- ---------- ----------
clerk 1900 950 1100 800
manager 2975 2975 2975 2975
analyst 6000 3000 3000 3000

SQL> select deptno,avg(sal) from emp group by deptno having count(*)>5;


DEPTNO AVG(SAL)
---------- ----------
30 2983.33333
SQL> select job,max(sal) from emp group by job having max(sal)>=500;
JOB MAX(SAL)
--------- ----------
salesman 10000
president 5000
clerk 1300
manager 2975
analyst 3000

SQL> select job,sum(sal),avg(sal),max(sal),min(sal) from emp where deptno=20


group by job having avg(sal)>1000;
JOB SUM(SAL) AVG(SAL) MAX(SAL) MIN(SAL)
--------- ---------- ---------- ---------- ----------
manager 2975 2975 2975 2975
analyst 6000 3000 3000 3000

SQL> select job,sum(sal),avg(sal),max(sal),min(sal) from emp where


deptno=20 group by job having avg(sal)>1000 order by sum(sal);
JOB SUM(SAL) AVG(SAL) MAX(SAL) MIN(SAL)
--------- ---------- ---------- ---------- ----------
manager 2975 2975 2975 2975
analyst 6000 3000 3000 3000

SQL> select ename from emp where sal=(select max(sal) from emp);
ENAME
---------
turner
SQL> select job,avg(sal) from emp group by job having avg(sal)=(select
max(avg(sal)) from emp group by job);
JOB AVG(SAL)
--------- ----------
president 5000

SQL> select * from emp where deptno=10 and exists(select count(*) from emp
where deptno=10 group by deptno having count(*) >10);

no rows selected

5) Queries on Controlling Data: Commit, Rollback, and Save point

SQL> create table student (sid number(3),sname varchar2(10),marks number(3));

Table created.

SQL> insert into student values(101,'sone',60);

1 row created.

SQL> insert into student values(102,'stwo',70);

1 row created.
SQL> select *from student;

SID SNAME MARKS


---------- ---------- ----------
101 sone 60
102 stwo 70

SQL> delete from student where sid=102;

1 row deleted.

SQL> select *from student


2 ;

SID SNAME MARKS


---------- ---------- ----------
101 sone 60

SQL> rollback;

Rollback complete.

SQL> select *from student;

SID SNAME MARKS


---------- ---------- ----------
101 sone 60
102 stwo 70

SQL> delete from student where sid=102;

1 row deleted.

SQL> select *from student;

SID SNAME MARKS


---------- ---------- ----------
101 sone 60

SQL> commit;

Commit complete.

SQL> select *from student;

SID SNAME MARKS


---------- ---------- ----------
101 sone 60

SQL> rollback;

Rollback complete.

SQL> select *from student;

SID SNAME MARKS


---------- ---------- ----------
101 sone 60

SQL> savepoint sp1;

Savepoint created.

SQL> insert into student values(102,'stwo',70);

1 row created.

SQL> savepoint sp2;

Savepoint created.

SQL> insert into student values(103,'sthr',80);

1 row created.

SQL> savepoint sp3;

Savepoint created.

SQL> insert into student values(104,'sfour',90);

1 row created.

SQL> select *from student;

SID SNAME MARKS


---------- ---------- ----------
101 sone 60
102 stwo 70
103 sthr 80
104 sfour 90
SQL> rollback to sp3;

Rollback complete.

SQL> select *from student;

SID SNAME MARKS


---------- ---------- ----------
101 sone 60
102 stwo 70
103 sthr 80

SQL> rollback to sp1;

Rollback complete.

SQL> select *from student;

SID SNAME MARKS


---------- ---------- ----------
101 ne 60

6) Queries to Build Report in SQL *PLUS


Changing a Column Heading:

SQL> column sal heading 'salary'


SQL> column comm heading 'commission'
SQL> select sal,comm from emp;

salary commission
---------- ----------
800
1600 300
1250 500
2975
1250 1400
2850
2450
3000
5000
1000 0
1100
950
3000
1300

14 rows selected.

Splitting a Column Heading:


SQL> column sal heading 'monthly|salary'
SQL> column comm heading 'monthly|comm'
SQL> select sal,comm from emp;

monthly monthly
salary comm
---------- -------
800
1600 300
1250 500
2975
1250 1400
2850
2450
3000
5000
1000 0
1100
950
3000
1300

14 rows selected.

Setting the Underline Character:

SQL> set underline=


SQL> select sal,comm from emp;

monthly monthly
salary comm
========== =======
800
1600 300
1250 500
2975
1250 1400
2850
2450
3000
5000
1000 0
1100
950
3000
1300

14 rows selected.

SQL> set underline#


SQL> select sal,comm from emp;

monthly monthly
salary comm
########## #######
800
1600 300
1250 500
2975
1250 1400
2850
2450
3000
5000
1000 0
1100
950
3000
1300

14 rows selected.

Formatting a NUMBER Column:

SQL> column sal format $9,999


SQL> select sal from emp;

monthly
salary
#######
$800
$1,600
$1,250
$2,975
$1,250
$2,850
$2,450
$3,000
$5,000
$1,000
$1,100
$950
$3,000
$1,300

14 rows selected.

To reset column display attributes and


SQL> COLUMN sal CLEAR
SQL> set underline ‘-‘
SQL> select sal from emp;

SAL
----------
800
1600
1250
2975
1250
2850
2450
3000
5000
1000
1100
950
3000
1300

14 rows selected.

Formatting a Character Column:

SQL> column ename format a4;


SQL> select ename from emp;

ENAM
----
smit
h

alle
n

ward
jone
s

mart
in

blak
e

clar
k

scot
t

king
turn
er

adem
s

jame
s

ford
mill
er

14 rows selected.

Resetting Column Display Attributes to their Defaults:

SQL> clear columns


columns cleared

Report generation using html file:

SQL> spool two.html


SQL> set markup html on
SQL&gt; select *from dept;
<br>
<p>
<table border='1' width='90%' align='center' summary='Script output'>
<tr>
<th scope="col">
DEPTNO
</th>
<th scope="col">
DNAME
</th>
<th scope="col">
LOC
</th>
</tr>
<tr>
<td align="right">
10
</td>
<td>
accounting
</td>
<td>
newyork
</td>
</tr>
<tr>
<td align="right">
20
</td>
<td>
research
</td>
<td>
dallas
</td>
</tr>
<tr>
<td align="right">
30
</td>
<td>
sales
</td>
<td>
chicago
</td>
</tr>
<tr>
<td align="right">
40
</td>
<td>
operations
</td>
<td>
goston
</td>
</tr>
</table>
<p>

SQL&gt; spool of
<br>
SQL&gt; spool off
<br>
SQL&gt; set markup html off
<br>
SQL>

two.html
Printing line at characters after wrapped column values:

SQL> column loc format a4


SQL> select loc from dept;

Output:

LOC
----
newy
ork

dall
as

chic
ago

gost
on

SQL> set recsepchar "-"


SQL> select loc from dept;

LOC
----
newy
ork
-------------------------------------------------------------------------------

dall
as
-------------------------------------------------------------------------------

chic
ago
-------------------------------------------------------------------------------

gost
on

7. Queries for Creating, Dropping, and Altering Tables, Views, and Constraints

Table:

SQL> Create table stud(sid number(4),sname varchar2(10));

Table created.

SQL> drop table stud;

Table dropped.

SQL> Create table stud(sid number(4),sname varchar2(10));

Table created.

SQL> alter table stud rename to studdd;

Table altered.

SQL> desc stud


ERROR:
ORA-04043: object stud does not exist

SQL> desc studdd;


Name Null? Type
----------------------------------------- -------- ----------------------------

SID NUMBER(4)
SNAME VARCHAR2(10)
SQL> alter table studdd add marks number(3);

Table altered.

SQL> desc studdd;


Name Null? Type
----------------------------------------- -------- ----------------------------

SID NUMBER(4)
SNAME VARCHAR2(10)
MARKS NUMBER(3)

SQL> alter table studdd modify marks varchar2(10);

Table altered.

SQL> desc studdd;


Name Null? Type
----------------------------------------- -------- ----------------------------

SID NUMBER(4)
SNAME VARCHAR2(10)
MARKS VARCHAR2(10)

SQL> alter table studdd drop column marks;

Table altered.

SQL> desc studdd;


Name Null? Type
----------------------------------------- -------- ----------------------------

SID NUMBER(4)
SNAME VARCHAR2(10)

SQL> alter table studdd rename column sname to studname;

Table altered.

SQL> desc studdd;


Name Null? Type
----------------------------------------- -------- ----------------------------

SID NUMBER(4)
STUDNAME VARCHAR2(10)

Views:

SQL> create or replace view emp_view as select empno,ename,sal from emp;

View created.

SQL> select *from emp_view;

EMPNO ENAME SAL


---------- ---------- ----------
7369 smith 800
7499 allen 1600
7521 ward 1250
7566 jones 2975
7654 martin 1250
7698 blake 2850
7782 clark 2450
7788 scott 3000
7839 king 5000
7844 turner 1000
7876 adems 1100
7900 james 950
7902 ford 3000
7934 miller 1300

14 rows selected.

SQL> create or replace view emp_view as select empno,ename,job,comm,deptno from


emp;

View created.

SQL> select *from emp_view;

EMPNO ENAME JOB COMM DEPTNO


---------- ---------- ---------- ---------- ----------
7369 smith clerk 20
7499 allen salesman 300 30
7521 ward salesman 500 30
7566 jones manager 20
7654 martin salesman 1400 30
7698 blake manager 30
7782 clark manager 10
7788 scott analyst 20
7839 king president 10
7844 turner salesman 0 30
7876 adems clerk 20
7900 james clerk 30
7902 ford analyst 20
7934 miller clerk 10

14 rows selected.

SQL> drop view emp_view;

View dropped.

SQL> desc emp_view;


ERROR:
ORA-04043: object emp_view does not exist

Constraints:

Not null

5* Age int
SQL> create table stud1(sid number(4)not null,fname varchar2(10)not null,lname v
archar2(10)not null,age number(3));

Table created.

SQL> desc stud1;


Name Null? Type
----------------------------------------- -------- ----------------------------

SID NOT NULL NUMBER(4)


FNAME NOT NULL VARCHAR2(10)
LNAME NOT NULL VARCHAR2(10)
AGE NUMBER(3)

SQL> drop table stud1;

Table dropped.

Unique

SQL> create table stud1(sid number(4)not null unique,fname varchar2(10)not null,


lname varchar2(10)not null,age number(3));

Table created.
SQL> desc stud1;
Name Null? Type
----------------------------------------- -------- ----------------------------

SID NOT NULL NUMBER(4)


FNAME NOT NULL VARCHAR2(10)
LNAME NOT NULL VARCHAR2(10)
AGE NUMBER(3)

SQL> drop table stud1;

Table dropped.

Primary key

SQL> create table stud1(sid number(4)primary key,fname varchar2(10)not null,lnam


e varchar2(10)not null,age number(3));

Table created.

SQL> desc stud1;


Name Null? Type
----------------------------------------- -------- ----------------------------

SID NOT NULL NUMBER(4)


FNAME NOT NULL VARCHAR2(10)
LNAME NOT NULL VARCHAR2(10)
AGE NUMBER(3)

SQL> drop table stud1;

Table dropped.

Foreign key

SQL> create table persons(pid number(4)primary key,fname varchar2(10)not null,ln


ame varchar2(10)not null,age number(3));

Table created.

SQL> desc persons;


Name Null? Type
----------------------------------------- -------- ----------------------------

PID NOT NULL NUMBER(4)


FNAME NOT NULL VARCHAR2(10)
LNAME NOT NULL VARCHAR2(10)
AGE NUMBER(3)

SQL> insert into persons values(101,'fone','lone',18);

1 row created.

SQL> insert into persons values(102,'ftwo','ltwo',19);

1 row created.

SQL> insert into persons values(103,'fthr','lthr',20);

1 row created.

SQL> commit;

Commit complete.

SQL> select *from persons;

PID FNAME LNAME AGE


---------- ---------- ---------- ----------
101 fone lone 18
102 ftwo ltwo 19
103 fthr lthr 20

SQL> create table orders(oid number(4)primary key,onumber number(4),pid number(4


),foreign key(pid) references persons(pid));

Table created.

SQL> desc orders;


Name Null? Type
----------------------------------------- -------- ----------------------------

OID NOT NULL NUMBER(4)


ONUMBER NUMBER(4)
PID NUMBER(4)

SQL> insert into persons values(11,1231,101);


insert into persons values(11,1231,101)
*
ERROR at line 1:
ORA-00947: not enough values
SQL> insert into orders values(11,1231,101);

1 row created.

SQL> insert into orders values(12,1232,101);

1 row created.

SQL> insert into orders values(13,1233,103);

1 row created.

SQL> insert into orders values(14,1234,103);

1 row created.

SQL> insert into orders values(15,1235,101);

1 row created.

SQL> commit;

Commit complete.

SQL> select *from orders;

OID ONUMBER PID


---------- ---------- ----------
11 1231 101
12 1232 101
13 1233 103
14 1234 103
15 1235 101

check

SQL> create table persons1(pid number(4)primary key,fname varchar2(10)not null,l


name varchar2(10)not null,age number(3),check (age>18));

Table created.

SQL> desc persons1;


Name Null? Type
----------------------------------------- -------- ----------------------------

PID NOT NULL NUMBER(4)


FNAME NOT NULL VARCHAR2(10)
LNAME NOT NULL VARCHAR2(10)
AGE NUMBER(3)

Add constraint

SQL> alter table studdd add constraint cons_fst primary key(sid);

Table altered.

SQL> desc studdd;


Name Null? Type
----------------------------------------- -------- ----------------------------

SID NOT NULL NUMBER(4)


STUDNAME VARCHAR2(10)

Drop constraint

SQL> alter table studdd drop constraint cons_fst ;

Table altered.

SQL> desc studdd;


Name Null? Type
----------------------------------------- -------- ----------------------------

SID NUMBER(4)
STUDNAME VARCHAR2(10)

8. Queries on Joins and Correlated Sub-Queries

Joins:
Inner join

SQL> select e.ename,e.sal,d.dname from emp e inner join dept d on e.deptno=d.dep


tno;

ENAME SAL DNAME


---------- ----- ----------
smith 800 research
allen 1600 sales
ward 1250 sales
jones 2975 research
martin 1250 sales
blake 2850 sales
clark 2450 accounting
scott 3000 research
king 5000 accounting
turner 1000 sales
adems 1100 research
james 950 sales
ford 3000 research
miller 1300 accounting

14 rows selected.

Outer joins

SQL> select e.ename,e.sal,d.dname from emp e left outer join dept d on e.deptn
d.deptno;

ENAME SAL DNAME


---------- ----- ----------
smith 800 research
allen 1600 sales
ward 1250 sales
jones 2975 research
martin 1250 sales
blake 2850 sales
clark 2450 accounting
scott 3000 research
king 5000 accounting
turner 1000 sales
adems 1100 research
james 950 sales
ford 3000 research
miller 1300 accounting

14 rows selected.

SQL> select e.ename,e.sal,d.dname from emp e right outer join dept d on e.dept
=d.deptno;

ENAME SAL DNAME


---------- ----- ----------
clark 2450 accounting
king 5000 accounting
miller 1300 accounting
jones 2975 research
ford 3000 research
adems 1100 research
smith 800 research
scott 3000 research
ward 1250 sales
turner 1000 sales
allen 1600 sales
james 950 sales
blake 2850 sales
martin 1250 sales
operations

15 rows selected.

SQL> select e.ename,e.sal,d.dname from emp e full outer join dept d on e.deptn
d.deptno;

ENAME SAL DNAME


---------- ----- ----------
smith 800 research
allen 1600 sales
ward 1250 sales
jones 2975 research
martin 1250 sales
blake 2850 sales
clark 2450 accounting
scott 3000 research
king 5000 accounting
turner 1000 sales
adems 1100 research
james 950 sales
ford 3000 research
miller 1300 accounting
operations

15 rows selected.

Equi join

SQL> select e.ename,e.job,e.sal,d.dname from emp e,dept d where e.deptno=d.deptn


o;

ENAME JOB SAL DNAME


---------- ---------- ----- ----------
smith clerk 800 research
allen salesman 1600 sales
ward salesman 1250 sales
jones manager 2975 research
martin salesman 1250 sales
blake manager 2850 sales
clark manager 2450 accounting
scott analyst 3000 research
king president 5000 accounting
turner salesman 1000 sales
adems clerk 1100 research
james clerk 950 sales
ford analyst 3000 research
miller clerk 1300 accounting

14 rows selected.

Self join

SQL> select d1.dname,d1.loc,d2.deptno from dept d1,dept d2 where d1.deptno< d2.d


eptno;

DNAME LOC DEPTNO


---------- -------- ------
accounting newyork 20
accounting newyork 30
research dallas 30
accounting newyork 40
research dallas 40
sales chicago 40

6 rows selected.

Cross join

SQL> select *from dept,salgrade;

DEPTNO DNAME LOC GRADE LOSAL HISAL


------ ---------- -------- ---------- ---------- ----------
10 accounting newyork 1 700 1200
10 accounting newyork 2 1201 1400
10 accounting newyork 3 1401 2000
10 accounting newyork 4 2001 3000
10 accounting newyork 5 3001 9999
20 research dallas 1 700 1200
20 research dallas 2 1201 1400
20 research dallas 3 1401 2000
20 research dallas 4 2001 3000
20 research dallas 5 3001 9999
30 sales chicago 1 700 1200
30 sales chicago 2 1201 1400
30 sales chicago 3 1401 2000
30 sales chicago 4 2001 3000
30 sales chicago 5 3001 9999
40 operations goston 1 700 1200
40 operations goston 2 1201 1400
40 operations goston 3 1401 2000
40 operations goston 4 2001 3000
40 operations goston 5 3001 9999

20 rows selected.

Sub quries:

Single row sub query

SQL> select ename,job,sal from emp where sal=(select min(sal) from emp);

ENAME JOB SAL


---------- ---------- -----
smith clerk 800

SQL> select ename,job,sal from emp where sal=(select max(sal) from emp);

ENAME JOB SAL


---------- ---------- -----
king president 5000

multiple row sub query

SQL> select ename,job,sal from emp where sal in(800,1000,1500,3000);

ENAME JOB SAL


---------- ---------- -----
smith clerk 800
scott analyst 3000
turner salesman 1000
ford analyst 3000

SQL> select ename,job,sal from emp where sal >any(select sal from emp where dept
no=30);

ENAME JOB SAL


---------- ---------- -----
king president 5000
ford analyst 3000
scott analyst 3000
jones manager 2975
blake manager 2850
clark manager 2450
allen salesman 1600
miller clerk 1300
ward salesman 1250
martin salesman 1250
adems clerk 1100
turner salesman 1000

12 rows selected.

SQL> select ename,job,sal from emp where sal <any(select sal from emp where dept
no=30);

ENAME JOB SAL


---------- ---------- -----
smith clerk 800
james clerk 950
turner salesman 1000
adems clerk 1100
ward salesman 1250
martin salesman 1250
miller clerk 1300
allen salesman 1600
clark manager 2450

9 rows selected.

SQL> select ename,job,sal from emp where sal >all(select sal from emp where dept
no=30);

ENAME JOB SAL


---------- ---------- -----
jones manager 2975
scott analyst 3000
king president 5000
ford analyst 3000

SQL> select ename,job,sal from emp where sal <all(select sal from emp where dept
no=30);

ENAME JOB SAL


---------- ---------- -----
smith clerk 800

SQL> select ename,job,sal from emp where sal =any(select sal from emp where dept
no=30);

ENAME JOB SAL


---------- ---------- -----
allen salesman 1600
martin salesman 1250
ward salesman 1250
blake manager 2850
turner salesman 1000
james clerk 950

6 rows selected.

Correlated sub query

SQL> select ename,job,sal from emp e where sal >(select min(losal) from salgrade
s where e.sal>s.losal);

ENAME JOB SAL


---------- ---------- -----
clark manager 2450
jones manager 2975
smith clerk 800
blake manager 2850
ford analyst 3000
james clerk 950
ward salesman 1250
allen salesman 1600
miller clerk 1300
king president 5000
adems clerk 1100
martin salesman 1250
turner salesman 1000
scott analyst 3000

14 rows selected.

Multiple column sub query

SQL> select ename,job,sal from emp where(sal,deptno) in (select sal,deptno from


emp_view where sal between 1000 and 3000);

ENAME JOB SAL


---------- ---------- -----
allen salesman 1600
martin salesman 1250
ward salesman 1250
jones manager 2975
blake manager 2850
clark manager 2450
ford analyst 3000
scott analyst 3000
turner salesman 1000
adems clerk 1100
miller clerk 1300

11 rows selected.

9. Queries on Working with Index, Sequence, Synonym, Controlling Access, and


Locking Rows for Update, Creating Password and Security features.

SQL> create index indx_fst on orders(onumber);

Index created.

SQL> select table_owner,table_name,index_name from user_indexes;

TABLE_OWNER TABLE_NAME INDEX_NAME


------------------------------ ------------------------- -----------------------
--
SCOTT PERSONS1 SYS_C004049
SCOTT PERSONS SYS_C004043
SCOTT ORDERS SYS_C004044
SCOTT ORDERS INDX_FST
SCOTT EMP SYS_C003998
SCOTT DEPT SYS_C003995

6 rows selected.

SQL> drop index indx_fst;

Index dropped.

Sequences:

SQL> create sequence sq_fst start with 1 increment by 2 maxvalue 10 minvalue 1 c


ache 3 cycle order;

Sequence created.

SQL> select sq_fst.nextval from dual;

NEXTVAL
----------
1
SQL> select sq_fst.currval from dual;

CURRVAL
----------
1

SQL> select *from user_sequences;

SEQUENC MIN_VALUE MAX_VALUE INCREMENT_BY C O CACHE_SIZE LAST_NUMBER


------- ---------- ---------- ------------ - - ---------- -----------
SQ_FST 1 10 2 Y Y 3 7

SQL> drop sequence sq_fst;

Sequence dropped.

Synonym:

SQL> create synonym order_syn for orders;

Synonym created.

SQL> select *from order_syn;

OID ONUMBER PID


---------- ---------- ----------
11 1231 101
12 1232 101
13 1233 103
14 1234 103
15 1235 101

SQL> create public synonym order_syn for orders;

Synonym created.

SQL> create public synonym order1_syn for orders;

Synonym created.

SQL> select *from order1_syn;

OID ONUMBER PID


---------- ---------- ----------
11 1231 101
12 1232 101
13 1233 103
14 1234 103
15 1235 101

SQL> drop synonym order_syn;

Synonym dropped.

Access control:

SQL> connect system/tiger;


Connected.
SQL> create user abc identified by xyz;

User created.

SQL> connect system/tiger;


Connected.
SQL> grant all privileges to abc;

Grant succeeded.

SQL> connect abc/xyz;


Connected.
SQL> connect system/tiger;
Connected.
SQL> alter user abc identified by pqr;

User altered.

SQL> connect abc/pqr;


Connected.

SQL> select username from user_users;

USERNAME

------------------------------

ABC

SQL> connect system/tiger;


Connected.

SQL> drop user abc;

User dropped.

10. Write a PL/SQL Code using Basic Variable, Anchored Declarations, and Usage of

Assignment Operation

declare
a integer := 10;
b integer := 20;
c integer;
f real;
v_ename emp.ename%type;
v_sal emp.sal%type;
begin
c := a + b;
dbms_output.put_line('Value of c: ' || c);
f := 70.0/3.0;
dbms_output.put_line('Value of f: ' || f);
select ename into v_ename from emp where empno=7844;
dbms_output.put_line(v_ename);
end;
/
Output:
Value of c: 30
Value of f: 23.33333333333333333333333333333333333333
turner

PL/SQL procedure successfully completed.

12. Write a PL/SQL Code Bind and Substitution Variables. Printing in PL/SQL

SQL> create table student


2 (rno number(5),
3 name varchar2(10),
4 s1 number(3),
5 s2 number(3),
6 s3 number(3),
7 s4 number(3),
8 total number(3),
9 avg number(7,2),
10 res varchar2(10));

SQL> desc student;


Name Null? Type
----------------------------------------- --------
----------------------------
RNO NUMBER(5)
NAME VARCHAR2(10)
S1 NUMBER(3)
S2 NUMBER(3)
S3 NUMBER(3)
S4 NUMBER(3)
TOTAL NUMBER(3)
AVG NUMBER(7,2)
RES VARCHAR2(10)
SQL> select * from student;
No rows selected
declare
x student%rowtype;
begin
x.rno:=&rno;
x.name:='&name';
x.s1:=&s1;
x.s2:=&s2;
x.s3:=&s3;
x.s4:=&s4;
x.total:=x.s1+x.s2+x.s3+x.s4;
x.avg:=x.total/4;
if((x.avg<=100) and (x.avg>=70)) then
x.res:='Distination';
dbms_output.put_line(x.res);
elsif((x.avg<=69) and (x.avg>=60)) then
x.res:='First Class';
dbms_output.put_line(x.res);
elsif((x.avg<=59) and (x.avg>=50)) then
x.res:='Second class';
dbms_output.put_line(x.res);
elsif((x.avg<=49) and (x.avg>=35)) then
x.res:='Third Class';
dbms_output.put_line(x.res);
else
x.res:='Fail';
dbms_output.put_line(x.res);
end if;
if(x.avg>100) then
raise_application_error(-200,'Not Valid Data');
end if;
insert into student
values(x.rno,x.name,x.s1,x.s2,x.s3,x.s4,x.total,x.avg,x.res);
commit;
end;

/
Enter value for rno: 41
old 4: x.rno:=&rno;
new 4: x.rno:=41;
Enter value for name:kba
old 5: x.name:='&name';
new 5: x.name:='kba';
Enter value for s1:67
old 6: x.s1:=&s1;
new 6: x.s1:=67;
Enter value for s2:89
old 7: x.s2:=&s2;
new 7: x.s2:=89;
Enter value for s3:56
old 8: x.s3:=&s3;
new 8: x.s3:=56;
Enter value for s4:90
old 9: x.s4:=&s4;
new 9: x.s4:=90;

PL/SQL procedure successfully completed.

SQL> /
Enter value for rno:56
old 4: x.rno:=&rno;
new 4: x.rno:=56;
Enter value for name:knsl
old 5: x.name:='&name';
new 5: x.name:='knsl';
Enter value for s1:89
old 6: x.s1:=&s1;
new 6: x.s1:=89;
Enter value for s2:90
old 7: x.s2:=&s2;
new 7: x.s2:=90;
Enter value for s3:78
old 8: x.s3:=&s3;
new 8: x.s3:=78;
Enter value for s4:88
old 9: x.s4:=&s4;
new 9: x.s4:=88;

PL/SQL procedure successfully completed.

SQL> /
Enter value for rno:36
old 4: x.rno:=&rno;
new 4: x.rno:=36;
Enter value for name:ks
old 5: x.name:='&name';
new 5: x.name:='ks';
Enter value for s1:65
old 6: x.s1:=&s1;
new 6: x.s1:=65;
Enter value for s2:77
old 7: x.s2:=&s2;
new 7: x.s2:=77;
Enter value for s3:82
old 8: x.s3:=&s3;
new 8: x.s3:=82;
Enter value for s4:92
old 9: x.s4:=&s4;
new 9: x.s4:=92;

PL/SQL procedure successfully completed.

SQL>/

Enter value for rno:33


old 4: x.rno:=&rno;
new 4: x.rno:=33;
Enter value for name:kur
old 5: x.name:='&name';
new 5: x.name:='kur';
Enter value for s1:69
old 6: x.s1:=&s1;
new 6: x.s1:=69;
Enter value for s2:55
old 7: x.s2:=&s2;
new 7: x.s2:=55;
Enter value for s3:98
old 8: x.s3:=&s3;
new 8: x.s3:=98;
Enter value for s4:76
old 9: x.s4:=&s4;
new 9: x.s4:=76;
PL/SQL procedure successfully completed.

SQL> select * from student;

RNO NAME S1 S2 S3 S4 TOTAL AVG RES


---------- ---------- ------ ------- ---------- ----- ------ --------
41 kba 67 89 56 90 302 75.5 Distination
56 knsl 89 90 78 88 345 86.2 Distination
36 ks 65 77 82 92 316 79 Distination
33 kur 69 55 98 76 298 74.5 Distination

12. Write a PL/SQL block using SQL and Control Structures in PL/SQL

SQL> create table e1


2 as
3 select * from emp;

Table created.

SQL> declare
2 x e1.sal%type;
3 y e1.eno%type;
4 bonus number(7,2);
5 begin
6 select sal,eno into x,y from e1
7 where eno=&eno;
8 if x between 500 and 1000 then
9 bonus:=500;
10 elsif x between 1001 and 2000 then
11 bonus:=1000;
12 elsif x between 2001 and 3000 then
13 bonus:=2000;
14 else
15 bonus:=3000;
16 end if;
17 update e1 set sal=sal+bonus
18 where eno=y;
19 end;
20 /
Enter value for eno: 7369
old 7: where eno=&eno;
new 7: where eno=7369;

PL/SQL procedure successfully completed.

SQL> /
Enter value for eno: 7499
old 7: where eno=&eno;
new 7: where eno=7499;

PL/SQL procedure successfully completed.

SQL> /
Enter value for eno: 7521
old 7: where eno=&eno;
new 7: where eno=7521;

PL/SQL procedure successfully completed.

SQL> /
Enter value for eno: 7566
old 7: where eno=&eno;
new 7: where eno=7566;

PL/SQL procedure successfully completed.

SQL> /
Enter value for eno: 7654
old 7: where eno=&eno;
new 7: where eno=7654;

PL/SQL procedure successfully completed.

SQL> /
Enter value for eno: 7698
old 7: where eno=&eno;
new 7: where eno=7698;

PL/SQL procedure successfully completed.

SQL> /
Enter value for eno: 7782
old 7: where eno=&eno;
new 7: where eno=7782;

PL/SQL procedure successfully completed.

SQL> /
Enter value for eno: 7839
old 7: where eno=&eno;
new 7: where eno=7839;

PL/SQL procedure successfully completed.

SQL> /
Enter value for eno: 7844
old 7: where eno=&eno;
new 7: where eno=7844;

PL/SQL procedure successfully completed.

SQL> /
Enter value for eno: 7876
old 7: where eno=&eno;
new 7: where eno=7876;

PL/SQL procedure successfully completed.

SQL> /
Enter value for eno: 7900
old 7: where eno=&eno;
new 7: where eno=7900;

PL/SQL procedure successfully completed.

SQL> /
Enter value for eno: 7902
old 7: where eno=&eno;
new 7: where eno=7902;

PL/SQL procedure successfully completed.

SQL> /
Enter value for eno: 7934
old 7: where eno=&eno;
new 7: where eno=7934;

PL/SQL procedure successfully completed.

SQL> select * from e1;

ENO ENAME JOB MGR HIREDATE SAL COMM DEPTNO PHNO


---------- ---------- ----------
7369 smith clerk 7902 17-DEC-80 2300 20
7499 allen salesmen 698 20-FEB-81 2600 300 30
7521 ward salesmen 7698 22-FEB-81 2250 500 30
7566 jones manager 7839 02-APR-81 4975 20
7654 martin salesme 7698 28-SEP-81 2250 1400 30
7698 blake manager 7839 01-MAY-81 4850 30
7782 clark manager 7839 09-JUN-81 4450 10
7788 scott analyist 7566 19-APR-87 3000 20
7839 king president 17-NOV-81 8000 10
7844 jurner salesmen 7698 08-SEP-81 2500 30
7876 adoms clerk 7788 23-MAY-87 2100 20
7900 james clerk 7698 03-DEC-81 1450 30
7902 ford analyist 7566 03-DEC-81 5000 20
7934 miller clerk 7782 23-JAN-82 2300 10

SQL> declare
2 x dept.Deptno%type;
3 begin
4 select Deptno into x from dept
5 where Deptno=&Deptno;
6 case x
7 when 10 then
8 dbms_output.put_line('Accounting');
9 when 20 then
10 dbms_output.put_line('Research');
11 when 30 then
12 dbms_output.put_line('Sales');
13 when 40 then
14 dbms_output.put_line('Operations');
15 else
16 dbms_output.put_line('Unknown Dept');
17 end case;
18 end;
19 /
Enter value for deptno: 10
old 5: where Deptno=&Deptno;
new 5: where Deptno=10;
Accounting

PL/SQL procedure successfully completed.

SQL> /
Enter value for deptno: 20
old 5: where Deptno=&Deptno;
new 5: where Deptno=20;
Research

PL/SQL procedure successfully completed.

SQL> /
Enter value for deptno: 30
old 5: where Deptno=&Deptno;
new 5: where Deptno=30;
Sales

PL/SQL procedure successfully completed.


SQL> /
Enter value for deptno: 40
old 5: where Deptno=&Deptno;
new 5: where Deptno=40;
Operations

PL/SQL procedure successfully completed.

SQL> /
Enter value for deptno: 60
old 5: where Deptno=&Deptno;
new 5: where Deptno=60;
declare
*
ERROR at line 1:
ORA-01403: no data found
ORA-06512: at line 4

13. Write a PL/SQL Code using Cursors, Exceptions and Composite Data Types
Cursors:
SQL> declare
2 veno e1.eno%type;
3 vename e1.ename%type;
4 vsal e1.sal%type;
5 vDeptno e1.Deptno%type;
6 cursor c1 is select eno,ename,sal,Deptno from e1
7 where sal+NVL(comm,0)>1500;
8 begin
9 open c1;
10 loop
11 fetch c1 into veno,vename,vsal,vDeptno;
12 if c1%found then
13 dbms_output.put_line(veno||' '||vename||' '||vsal||' '||vDeptno);
14 else
15 exit;
16 end if;
17 end loop;
18 close c1;
19 end;
20 /
7499 allen 1600 30
7521 ward 2524 30
7566 jones 3570 20
7654 martin 1250 30
7698 blake 2850 30
7782 clark 2450 10
7788 scott 3000 20
7839 king 5000 10
7902 ford 3000 20
7934 miller 2246.4 10
PL/SQL procedure successfully completed.

SQL> declare
2 salary e1.sal%type;
3 s number:=0;
4 cursor c1 is select sal from e1;
5 begin
6 open c1;
7 loop
8 fetch c1 into salary;
9 s:=s+salary;
10 exit when c1%notfound;
11 update emp set sal=sal+sal*10/100
12 where Deptno=20 and Deptno=40;
13 end loop;
14 dbms_output.put_line('Total is: ');
15 dbms_output.put_line(to_char(s));
16 dbms_output.put_line('Rows Fetched'||c1%rowcount);
17 close c1;
18 end;
19 /
Total is:
34276.8
Rows Fetched14

PL/SQL procedure successfully completed.

SQL> declare
2 i number;
3 cursor c2 is
4 select * from e1
5 where Deptno=20
6 for update of sal;
7 begin
8 for i in c2
9 loop
10 update e1 set sal=10000
11 where current of c2;
12 end loop;
13 end;
14 /

PL/SQL procedure successfully completed.

SQL> select * from emp


2 where Deptno=20;

ENO ENAME JOB MGR HIREDATE SAL COMM DEPTNO PHNO


7369 smith clerk 7902 17-DEC-80 800 20
7566 jones manager 7839 02-APR-81 2975 20
7788 scott analyist 7566 19-APR-87 3000 20
7876 adoms clerk 7788 23-MAY-87 1100 20
7902 ford analyist 7566 03-DEC-81 3000 20
SQL> select * from e1
2 where Deptno=20;

ENO ENAME JOB MGR HIREDATE SAL


---------- ---------- ---------- ---------- ------------------ ----------
COMM DEPTNO PHNO
---------- ---------- ----------
7369 smith clerk 7902 17-DEC-80 10000
20
7566 jones manager 7839 02-APR-81 10000
20
7788 scott analyist 7566 19-APR-87 10000
20
7876 adoms clerk 7788 23-MAY-87 10000
20
7902 ford analyist 7566 03-DEC-81 10000
20

Exceptions:

system defined exception


SQL> declare
2 x e1.job%type;
3 begin
4 select job into x from e1 where job='&job';
5 dbms_output.put_line(x||'Job type appeared only once');
6 commit;
7 exception
8 when too_many_rows then
9 dbms_output.put_line(x||'Job type Found more than Once');
10 commit;
11 when no_data_found then
12 dbms_output.put_line(x||'Job type not Found');
13 end;
14 /

Enter value for job: salesmen


old 4: select job into x from e1 where job='&job';
new 4: select job into x from e1 where job='salesmen';
salesmenJob type Found more than Once
PL/SQL procedure successfully completed.

SQL> /
Enter value for job: president
old 4: select job into x from e1 where job='&job';
new 4: select job into x from e1 where job='president';
presidentJob type appeared only once

PL/SQL procedure successfully completed.


SQL> /
Enter value for job: student
old 4: select job into x from e1 where job='&job';
new 4: select job into x from e1 where job='student';
Job type not Found

PL/SQL procedure successfully completed.

user defined exception


SQL> declare
2 e exception;
3 n number:=&n;
4 f number:=1;
5 i number;
6 begin
7 if n<0 then
8 raise e;
9 end if;
10 for i in 1..n
11 loop
12 f:=f*i;
13 end loop;
14 dbms_output.put_line('factorial of n is'||f);
15 exception
16 when e then
17 dbms_output.put_line('factorial for negative numbers is an error');
18 end;
19 /
Enter value for n: 5
old 3: n number:=&n;
new 3: n number:=5;
factorial of n is120
PL/SQL procedure successfully completed.
SQL> /
Enter value for n: -2
old 3: n number:=&n;
new 3: n number:=-2;
factorial for negative numbers is an error
PL/SQL procedure successfully completed.

14.Write a PL/SQL Code using Procedures, Functions, and Packages FORMS


Procedures:
a.procedure to compute factorial of a number
SQL> create or replace procedure factorial(n number) IS
2 f number:=1;
3 i number;
4 e exception;
5 begin
6 if n<0 then
7 raise e;
8 end if;
9 for i in 1..n
10 loop
11 f:=f*i;
12 end loop;
13 dbms_output.put_line('factorial of'||n||'is'||f);
14 exception
15 when e then
16 dbms_output.put_line('factorial for negative numbers donot exist');
17 end factorial;
18 /

Procedure created.

SQL> /

Procedure created.

SQL> set serveroutput on;


SQL> execute factorial(4);
factorial of4is24

PL/SQL procedure successfully completed.


SQL> execute factorial(-9);
Factorial for Negative Number donot exists

PL/SQL procedure successfully completed.

SQL> execute factorial(-6);


Factorial for Negative Number donot exists

PL/SQL procedure successfully completed.

b.procedure to increment emp sal


SQL> create or replace procedure a(eid number) IS
2 incr e1.sal%type;
3 net e1.sal%type;
4 veno e1.eno%type;
5 vsal e1.sal%type;
6 vcomm e1.comm%type;
7 begin
8 select eno,sal,NVL(comm,0) into veno,vsal,vcomm from e1
9 where eno=eid;
10 net:=vsal+vcomm;
11 if vsal<=3000 then
12 incr:=0.20*net;
13 elsif vsal>=3000 and vsal<=6000 then
14 incr:=0.40*net;
15 else
16 incr:=0.40*net;
17 end if;
18 update e1 set sal=sal+incr where eno=eid;
19 exception
20 when no_data_found then
21 dbms_output.put_line('emp doesnot exist');
22 end a;
23 /

Procedure created.
SQL> select eno,sal from e1 where eno=7369;
ENO SAL
---------- ----------
7369 960

SQL> execute a(7369);


PL/SQL procedure successfully completed.

SQL> select eno,sal from e1 where eno=7369;


ENO SAL
---------- ----------
7369 1152

.
SQL> select eno,sal from emp where eno=7934;
ENO SAL
---------- ----------
7934 1300

SQL> select eno,sal from emp where eno=7521;


ENO SAL
---------- ----------
7521 1250

SQL> execute a(7521);


PL/SQL procedure successfully completed.

SQL> execute a(7934);


PL/SQL procedure successfully completed.
SQL> execute a(5414);
emp not exists

PL/SQL procedure successfully completed.

Functions:

a.
1 create or replace function fact(n number,f in out number) return number
IS
2 i number;
3 begin
4 if n<0 then
5 return -1;
6 end if;
7 for i in 1..n
8 loop
9 f:=f*i;
10 end loop;
11 return f;
12* end fact;
SQL> /

Function created.

1 declare
2 n number:=&n;
3 f number:=1;
4 k number;
5 begin
6 k:=fact(n,f);
7 if k<0 then
8 dbms_output.put_line('factorial for negative numbers donot exist');
9 else
10 dbms_output.put_line('factorial is'||k);
11 end if;
12* end;
13 /
Enter value for n: 4
old 2: n number:=&n;
new 2: n number:=4;
Factorial is24
PL/SQL procedure successfully completed.

SQL> /
Enter value for n: 6
old 2: n number:=&n;
new 2: n number:=6;
Factorial is720
PL/SQL procedure successfully completed.

SQL> /
Enter value for n: -6
old 2: n number:=&n;
new 2: n number:=-6;
Factorial for Negative Numbers not exist
PL/SQL procedure successfully completed.
b.
1 create or replace function a1(eid number) return number IS
2 incr e1.sal%type;
3 net e1.sal%type;
4 veno e1.eno%type;
5 vsal e1.sal%type;
6 vcomm e1.comm%type;
7 begin
8 select eno,sal,NVL(comm,0) into veno,vsal,vcomm from e1
9 where eno=eid;
10 net:=vsal+vcomm;
11 if vsal<=3000 then
12 incr:=0.20*net;
13 elsif vsal>=3000 and vsal<=6000 then
14 incr:=0.30*net;
15 else
16 incr:=0.40*net;
17 end if;
18 return incr;
19* end a1;
20 /

Function created.

SQL> ed;
Wrote file afiedt.buf

1 declare
2 eid number:=&eid;
3 k e1.sal%type;
4 begin
5 k:=a1(eid);
6 update e1 set sal=sal+k where eno=eid;
7* end;
8 /
Enter value for eid: 7369
old 2: eid number:=&eid;
new 2: eid number:=7369;

PL/SQL procedure successfully completed.

SQL> select eno,sal from e1 where eno=7369;

ENO SAL
---------- ----------
7369 1990.66
Packages:

a.
1 create or replace package p1 is
2 procedure p_empdept1(dn NUMBER);
3* end p1;
SQL> /

Package created.

SQL> ed;
Wrote file afiedt.buf

1 create or replace package body p1 is


2 procedure p_empdept1(dn in number) is dummydept number;
3 begin
4 select distinct dn into dummydept from emp where deptno=dn;
5 dbms_output.put_line('dept number present');
6 exception
7 when no_data_found then
8 dbms_output.put_line('dept number not present');
9 end;
10* end p1;
SQL> /

Package body created.

SQL> execute p1.p_empdept1(20);


dept number present

PL/SQL procedure successfully completed.

SQL> execute p1.p_empdept1(50);


dept number not present

PL/SQL procedure successfully completed.

b. SQL> create or replace package p2 is procedure fact3(n number);


2 end p2;
3 /

Package created.

SQL> create or replace package body p2 is procedure fact3(n in number) is


2 f number:=1;
3 i number;
4 e exception;
5 begin
6 if n<0 then raise e;
7 end if;
8 for i in 1..n
9 loop
10 f:=f*i;
11 end loop;
12 dbms_output.put_line('factorial of'||n||'is'||f);
13 exception
14 when e then
15 dbms_output.put_line('not possible');
16 end fact3;
17 end p2;
18 /

Package body created.

SQL> set serveroutput on;


SQL> execute p2.fact3(4);
factorial of4is24
PL/SQL procedure successfully completed.

SQL> execute p2.fact3(-4);


not possible
PL/SQL procedure successfully completed.

SQL> execute p2.b(6);


factorial 6is720
PL/SQL procedure successfully completed.
SQL> execute p2.b(-6);
Not possible
PL/SQL procedure successfully completed.

SQL> execute p2.b(7);


factorial 7is5040
PL/SQL procedure successfully completed.

SQL> execute p2.b(-7);


Not possible
PL/SQL procedure successfully completed.

17. Write a PL/SQL Code Creation of forms for any Information System such as Student Information
System, Employee Information System etc.
Click on login

Click on create application in above and give in Name field as ‘app1’ and click on next below

Select Form check box and select any table from the list of tables like EMP in Table Name field and click add
page in below
Click emp link
16.Demonstration of database connectivity

Java Program to connect to oracle DB:

import java.sql.*;
class ConnectToOraDB {
public static void main(String args[])throws Exception{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","scott","tiger");
System.out.println("..........Connected to Oracle Database......"+con.getClass());
}
}
Output:

E:\acedamic\f\j2ee\jdbc>javac ConnectToOraDB.java

E:\acedamic\f\j2ee\jdbc>java ConnectToOraDB
..........Connected to Oracle Database......class oracle.jdbc.driver.OracleConne
Ction
Java program to create table in oracle DB:
import java.sql.*;
class CreateTable {
public static void main(String args[])throws Exception{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","scott","tiger");
System.out.println("..........Connected to Oracle Database...........");
Statement stmt=con.createStatement();
String sql="create table std(sid number(4),sname varchar2(10),marks number(3))";
stmt.executeUpdate(sql);
}
}
Output:

E:\acedamic\f\j2ee\jdbc>javac CreateTable.java

E:\acedamic\f\j2ee\jdbc>java CreateTable
..........Connected to Oracle Database...........

E:\acedamic\f\j2ee\jdbc>
Output:

SQL> desc std;


Name Null? Type
----------------------------------------- -------- ---------------------------

SID NUMBER(4)
SNAME VARCHAR2(10)
MARKS NUMBER(3)

SQL>
Java program to insert rows into a table:
import java.sql.*;
class InsertUsingStatement {
public static void main(String args[])throws Exception{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","scott","tiger");
System.out.println("..........Connected to Oracle Database...........");
Statement stmt=con.createStatement();
String sql1="insert into std values(1001,'sone',60)";
String sql2="insert into std values(1002,'stwo',70)";
String sql3="insert into std values(1003,'sthr',80)";
stmt.executeUpdate(sql1);
stmt.executeUpdate(sql2);
stmt.executeUpdate(sql3);
}
}
Output:
E:\acedamic\f\j2ee\jdbc>java InsertUsingStatement
..........Connected to Oracle Database...........

SQL> select *from std;

SID SNAME MARKS


---------- ---------- ----------
1001 sone 60
1002 stwo 70
1003 sthr 80

SQL>
Java program to select rows from table:
import java.sql.*;
class SelectingRowsUsingResultSet {
public static void main(String args[])throws Exception{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","scott","tiger");
System.out.println("..........Connected to Oracle Database...........");
String sql="select *from std";
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery(sql);
while(rs.next()){
System.out.println("row......>"+rs.getRow());
System.out.print(rs.getInt(1)+" ");
System.out.print(rs.getString(2)+" ");
System.out.println(rs.getInt(3)+" ");
}

}
}

Output:
E:\acedamic\f\j2ee\jdbc>java SelectingRowsUsingResultSet
..........Connected to Oracle Database...........
row......>1
1001 sone 60
row......>2
1002 stwo 70
row......>3
1003 sthr 80

E:\acedamic\f\j2ee\jdbc>

You might also like