0% found this document useful (0 votes)
90 views

Dbms r20 Lab Manual Final

Uploaded by

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

Dbms r20 Lab Manual Final

Uploaded by

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

INTERNATIONAL SCHOOL OF TECHNOLOGY & SCIENCES

Department of Computer Science and Engineering

II B.TECH I SEM

Database Management Systems (R2022056)

Lab Manual
Regulation: R20
INTERNATIONAL SCHOOL OF TECHNOLOGY & SCIENCES

Department of Computer Science and Engineering


INDEX

Page
S.No Practical’s Name
Number
1 Creation, altering and dropping of tables and inserting rows 1 -7
into a table (use constraints while creating tables) examples
using SELECT command
2 Queries (along with sub Queries) using ANY, ALL, IN, 8-12
EXISTS, NOTEXISTS, UNION, INTERSET, Constraints.
Example:- Select the roll number and name of the student
who secured fourth rank in the class
3 Queries using Aggregate functions (COUNT, SUM, AVG, 13-15
MAX and MIN), GROUP BY, HAVING and Creation and
dropping of Views
4 Queries using Conversion functions (to_char, to_number 16-23
and to_date), string functions (Concatenation, lpad, rpad,
ltrim, rtrim, lower, upper, initcap, length, substr and instr),
date functions (Sysdate, next_day, add_months, last_day,
months_between, least, greatest, trunc, round, to_char,
to_date)
5 i. Create a simple PL/SQL program which includes 24-26
declaration section, executable section and exception –
Handling section (Ex. Student marks can be selected from
the table and printed for those who secured first class and
an exception can be raised if no records were found) ii.
Insert data into student table and use COMMIT,
ROLLBACK and SAVEPOINT in PL/SQL block.
6 Develop a program that includes the features NESTED IF, 27- 28
CASE and CASE expression. The program can be
extended using the NULLIF and COALESCE functions
7 Program development using WHILE LOOPS, numeric 29- 31
FOR LOOPS, nested loops using ERROR Handling,
BUILT –IN Exceptions, USE defined Exceptions,
RAISEAPPLICATION ERROR
8 Programs development using creation of procedures, 32
passing parameters IN and OUT of PROCEDURES
9 Program development using creation of stored functions, 33
invoke functions in SQL Statements and write complex
functions.
10 Develop programs using features parameters in a CURSOR, 34
FOR UPDATE CURSOR, WHERE CURRENT of clause
and CURSOR variables

11 Develop Programs using BEFORE and AFTER Triggers, 35-37


Row and Statement Triggers and INSTEAD OF Triggers

12 Create a table and perform the search operation on table 38-39


using indexing and non indexing techniques

Add-on Programs

1 Queries on Joins. 40-41

2 Write a PL/SQL Code Bind and Substitution Variables. 42-44


Printing in PL/SQL.

3 Demonstration of database connectivity 45


Database Management Systems Lab Manual

WEEK-1

AIM: Creation, altering and dropping of tables and inserting rows into a table (use constraints while
creating tables) examples using SELECT command.

a) create the following relations using appropriate SQL statements:


DEPT (DEPTNO: NUMBER(2), DNAME: VARCHAR2(10), LOC: VARCHAR2(8))
EMP(EMPNO:NUMBER(4),ENAME:VARCHAR2(9),JOB: VARCHAR2(9),MGR:NUMBER(4),
HIREDATE:DATE,SAL:NUMBER(7,2),COMM.:NUMBER(7,2),DEPTNO:NUMBER(2))

SALGRADE (GRADE:NUMBER(1),LOSAL:NUMBER(4),HISAL:NUMBER(4))
EMP relation provides information about the employees. DEPT relation provides information about
departments and SALGRADE relation provides information about the grades based on the salaries of the
employees.

 Define a constraint on EMP relation that will ensure that every employee earns atmost
Rs.10000/-
 Define constraint on EMP relation such that deptno will be foreign key to DEPT relation
 Define dept’s relation so that every department is guaranteed to have some name.
SQL>CREATE TABLE DEPT (DEPTNO NUMBER (2) PRIMARY KEY, DNAME VARCHAR2 (10)
NOT NULL, LOC VARCHAR2 (8));
Table created.

SQL>CREATE TABLE EMP(EMPNO NUMBER(4) PRIMARY KEY,ENAME VARCHAR2(9),JOB


VARCHAR2(9),MGR NUMBER(4),HIREDATE DATE,SAL NUMBER(7,2)
CHECK(SAL<=10000),COMM NUMBER(7,2),DEPTNO NUMBER(2) ,FOREIGN KEY(DEPTNO)
REFERENCES DEPT);
Table created

SQL>CREATE TABLE SALGRADE (GRADE NUMBER (1), LOSAL NUMBER (4), HISAL NUMBER
(4));
Table created.

b) AIM: To Alter the tables using appropriate SQL statements:

1) Alter the size of dname of DEPT table


SQL> ALTER TABLE DEPT MODIFY (DNAME VARCHAR2 (20));
Table altered.

Department of Computer Science and Engineering Page 1


Database Management Systems Lab Manual

2) Alter the SALGRADE table by adding constraint unique to the field grade
SQL> ALTER TABLE SALGRADE ADD CONSTRAINT CONS_GRADE UNIQUE (GRADE);
Table altered.

3) Alter the SALGRADE table by dropping constraint unique to the field grade
SQL> ALTER TABLE SALGRADE DROP CONSTRAINT CONS_GRADE;

Table altered.

c) AIM: Dropping the tables using appropriate SQL statements

1) Drop the EMP table


SQL> DROP TABLE EMP;
Table dropped.

2) Drop the DEPT table


SQL> DROP TABLE DEPT;
Table dropped.

d) AIM: To insert the following data into appropriate relations:


DEPT
DEPTNO DNAME LOC
10 ACCOUNTING NEWYORK 20
RESEAR CH DALLAS 30
SALES CHICAGO 40
OPERATIONS BOSTON

EMP
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO

7369 SMITH CLERK 7902 17-De-80 800 20


7499 ALLEN SALESMAN 7698 20-Fe-81 1600 300 30
7521 WARD SALESMAN 7698 22-Fe-81 1250 500 30
7566 JONES MANAGER 7839 02-Apr-81 2975 20
7654 MARTIN SALESMAN 7698 28-Se-81 1250 1400 30
7698 BLAKE MANAGER 7839 01-May81 2850 30
7782 CLARK MANAGER 7839 09-Jun-81 2450 10

Department of Computer Science and Engineering Page 2


Database Management Systems Lab Manual

7788 SCOTT ANALYST 7566 19-Apr-87 3000 20


7839 KING PRESIDENT 17-No-81 5000 10

7844 TURNER SALESMAN 7698 08-Se-81 1500 0 30

7876 ADAMS CLERK 7788 23-May87 1100 20

7900 JAMES CLERK 7698 03-De-81 950 30

SALGRADE

GRADE LOSAL HISAL


1 700 1200
2 1201 1400
3 1401 2000
4 2001 3000
5 3001 9999
MULTI ROW INSERTIONS
1) SQL> INSERT INTO DEPT (DEPTNO, DNAME, LOC) VALUES(&DEPTNO,'&DNAME','&LOC');

Enter value for deptno: 10


Enter value for dname: ACCOUNTING
Enter value for loc: NEWYORK
old 1: INSERT INTO DEPT VALUES(&DEPTNO,'&DNAME','&LOC')
new 1: INSERT INTO DEPT VALUES(10,'ACCOUNTING','NEWYORK')

1 row created.
2) SQL> INSERT INTO EMP(EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO)

VALUES(&EMPNO,’&ENAME’,’&JOB’,&MGR,’&HIREDATE’,&SAL,&COMM,&DEPTNO);

Enter value for empno: 7499


Enter value for ename: ALLEN
Enter value for job: SALESMAN
Enter value for mgr: 7698
Department of Computer Science and Engineering Page 3
Database Management Systems Lab Manual

Enter value for hiredate: 20-FEB-81

Enter value for sal: 1600

Enter value for comm: 300


Enter value for deptno: 30
old 1: INSERT INTO EMP(EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO)
new 1: INSERT INTO EMP(7499,’ALLEN’,’SALESMAN’,7698,’20-FEB-81’,1600,300,30) 1
row created.

3) SQL> INSERT INTO SALGRADE (GRADE,LOSAL,HISAL)


VALUES(&GRADE,&LOSAL,&HISAL);

Enter value for grade: 5


Enter value for losal: 3001
Enter value for hisal: 9999
old 1: INSERT INTO SALGRADE (GRADE,LOSAL,HISAL)
VALUES(&GRADE,&LOSAL,&HISAL)
new 1: INSERT INTO SALGRADE (GRADE,LOSAL,HISAL) VALUES(5,3001,9999)
1 row created.

SINGLE ROW INSERTIONS


SQL> INSERT INTO DEPT(DEPTNO,DNAME,LOC) VALUES(20,'RESEARCH','DALLAS')
1 row created.

SQL> INSERT INTO EMP(EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO)


VALUES(7521,’WARD’,’SALESMAN’,7698,’22-FEB-81’,1250,500,30);
1 row created.

SQL> INSERT INTO SALGRADE (GRADE,LOSAL,HISAL) VALUES(4,2001,3000);


1 row created.

e) AIM : To retrieve the data from the relations of the database using the following queries.
1) Display names of the employees’.
SQL>SELECT ENAME FROM EMP;

Department of Computer Science and Engineering Page 4


Database Management Systems Lab Manual

ENAME

SMITH
ALLEN
WARD
JONES
MARTIN
BLAKE
CLARK
SCOTT
KING
TURNER
14 rows selected.
2) Find all employees who are managers.
SELECT * FROM EMP WHERE JOB=’MANAGER’;
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO

7566 JONES MANAGER 7839 02-APR-81 2975 20


7698 BLAKE MANAGER 7839 01-MAY-81 2850 30
7782 CLARK MANAGER 7839 09-JUN-81 2450 10
3) List all clerks in deptno. 30.

SQL> SELECT EMPNO,ENAME,JOB FROM EMP WHERE JOB='CLERK' AND DEPTNO=30;

EMPNO ENAME JOB

7900 JAMES CLERK

4) List all distinct jobs.


SQL> SELECT DISTINCT (JOB) FROM EMP;
JOB

ANALYST
CLERK
MANAGER
PRESIDENT
SALESMAN
5) List employee names whose salary is between 2000 and 3000.

SQL> SELECT ENAME,SAL FROM EMP WHERE SAL BETWEEN 2000 AND 3000;

Department of Computer Science and Engineering Page 5


Database Management Systems Lab Manual

ENAME SAL

JONES 2975
BLAKE 2850
CLARK 2450
SCOTT 3000
FORD 3000
6) List employee names in alphabetical order.

SQL> SELECT ENAME FROM EMP ORDER BY ENAME;

ENAME

ADAMS
ALLEN
BLAKE
CLARK
FORD
JAMES
JONES
KING
MARTIN
MILLER
SCOTT
SMITH
TURNER
WARD
14 rows selected.

7) List employee names whose commission is NULL.

SQL> SELECT ENAME FROM EMP WHERE COMM IS NULL;

ENAME

SMITH
JONES
BLAKE
CLARK
SCOTT
KING
ADAMS
JAMES
Department of Computer Science and Engineering Page 6
Database Management Systems Lab Manual

FORD
MILLER
10 rows selected.

8) List jobs that are unique to deptno 20

SQL> SELECT DISTINCT (JOB) FROM EMP WHERE DEPTNO=20;

JOB

ANALYST
CLERK
MANAGER

Department of Computer Science and Engineering Page 7


Database Management Systems Lab Manual

WEEK 2
AIM: Queries (along with sub Queries) using ANY, ALL, IN, EXISTS, NOTEXISTS, UNION,
INTERSET, Constraints. Example:- Select the roll number and name of the student who secured
fourth rank in the class
1) Display employees who earn more than the lowest salary in department 30.
SQL>SELECT ENAME, SAL FROM EMP WHERE SAL>ANY(SELECT DISTINCT SAL FROM EMP
WHERE DEPTNO=30);

ENAME SAL

ALLEN 1600
WARD 1250
JONES 2975
MARTIN 1250
BLAKE 2850
CLARK 2450

SCOTT 3000
KING 5000
TURNER 1500
ADAMS 1100
FORD 3000
MILLER 1300

12 rows selected.

2) Display employees who earn more than every employee in department 30.
SELECT ENAME, SAL FROM EMP WHERE SAL>ALL (SELECT DISTINCT SAL FROM EMP
WHERE DEPTNO=30);

ENAME SAL

JONES 2975

Department of Computer Science and Engineering Page 8


Database Management Systems Lab Manual

SCOTT 3000
KING 5000

3) Find the names of employees who are working in ‘CHICAGO’.


SQL> SELECT E.ENAME FROM EMP E WHERE E.DEPTNO IN (SELECT D.DEPTNO FROM DEPT
D WHERE D.LOC='CHICAGO');
ENAME

ALLEN

WARD
MARTIN
BLAKE
TURNER
JAMES
6 rows selected.

4) Find the names of employees who are not working in ‘CHICAGO’.


SQL> SELECT E.ENAME FROM EMP E WHERE E.DEPTNO NOT IN (SELECT D.DEPTNO FROM
DEPT D WHERE D.LOC='CHICAGO');
ENAME

SMITH
JONES
CLARK

SCOTT
KING

ADAMS

Department of Computer Science and Engineering Page 9


Database Management Systems Lab Manual

FORD

MILLER

8 rows selected.
5) Find the names of employees who are working in ‘CHICAGO’.
SQL> SELECT E.ENAME FROM EMP E WHERE EXISTS (SELECT * FROM DEPT D WHERE
D.DEPTNO=E.DEPTNO AND D.LOC='CHICAGO');
ENAME

ALLEN

WARD
MARTIN
BLAKE
TURNER
JAMES

6 rows selected.

6) Find the names of employees who are not working in ‘CHICAGO’.


SQL> SELECT E.ENAME FROM EMP E WHERE NOT EXISTS (SELECT * FROM DEPT D WHERE
D.DEPTNO=E.DEPTNO AND D.LOC='CHICAGO');

ENAME

SMITH
JONES
CLARK

SCOTT
KING
ADAMS

Department of Computer Science and Engineering Page 10


Database Management Systems Lab Manual

FORD

MILLER

8 rows selected.
7) Find the names of the employees who are working in either ‘DALLAS’ or ‘NEW YORK’.
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='NEW
YORK';
ENAME

ADAMS
CLARK
FORD

JONES
KING
MILLER

SCOTT
SMITH
8 rows selected.
8) Display the department numbers that has employee.
SQL> SELECT E.DEPTNO FROM EMP E INTERSECT SELECT D.DEPTNO FROM DEPT D;
DEPTNO

10

20
30

Department of Computer Science and Engineering Page 11


Database Management Systems Lab Manual

9) Display the department numbers that has no employee.

SQL> SELECT DEPTNO FROM DEPT MINUS SELECT DEPTNO FROM EMP;
DEPTN
40

Department of Computer Science and Engineering Page 12


Database Management Systems Lab Manual

WEEK-3
AIM: Queries using Aggregate functions (COUNT, SUM, AVG, MAX and MIN), GROUP BY, HAVING
and Creation and dropping of Views.

a) Queries using Aggregate functions, GROUP BY, HAVING and Creation and dropping of Views

1) Find the number of rows in the EMP table.


SQL> SELECT COUNT(*) FROM EMP;
COUNT(*)

14

2) List the numbers of jobs.


SQL> SELECT COUNT(DISTINCT(JOB)) AS TOTALJOBS FROM EMP;
TOTALJOBS

3) Find total salary of the EMP table


SQL> SELECT SUM(SAL) AS TOTALSALARY FROM EMP;
TOTALSALARY

29025

4) List maximum sal, minimum sal, average sal of EMP table


SQL> SELECT MAX(SAL),MIN(SAL),AVG(SAL) FROM EMP;
MAX(SAL) MIN(SAL) AVG(SAL)

5000 800 2073.21429

5) List the numbers of people and average salary in deptno 30.


SQL> select count(*),avg(sal) from emp where deptno=30;

Department of Computer Science and Engineering Page 13


Database Management Systems Lab Manual

COUNT(*) AVG(SAL)

6 1666.66667

6) List maximum sal and minimum sal in the designations SALESMAN and CLERK.
SQL> SELECT COUNT(*),MAX(SAL),MIN(SAL),AVG(SAL) FROM EMP WHERE JOB
IN('SALESMAN','CLERK');

COUNT(*) MAX(SAL) MIN(SAL) AVG(SAL)

8 1600 800 1218.75

7) ) Calculate total salary bill for each department.


SQL>SELECT DEPTNO,SUM(SAL) AS TOTALSAL FROM EMP GROUP BY DEPTNO;
DEPTNO TOTALSAL

10 8750
20 10875
30 9400

8) List max sal, min sal and average sal of depts. 10,30.
SQL> SELECT DEPTNO,MIN(SAL),MAX(SAL),AVG(SAL) FROM EMP WHERE DEPTNO
IN(10,30) GROUP BY DEPTNO;

DEPTNO MIN(SAL) MAX(SAL) AVG(SAL)

10 1300 5000 2916.66667


30 950 2850 1566.66667
9) Find all departments which having more than 3 employees.
SQL> SELECT DEPTNO,COUNT(*) FROM EMP GROUP BY DEPTNO HAVING COUNT(*)>3;
DEPTNO COUNT(*)

20 5

Department of Computer Science and Engineering Page 14


Database Management Systems Lab Manual

30 6

10) Display the jobs where the minimum salary is greater than or equal to 3000.
SQL> SELECT JOB,MIN(SAL) FROM EMP GROUP BY JOB HAVING MIN(SAL)>=3000;

JOB MIN(SAL)

ANALYST 3000
PRESIDENT 5000

b) AIM: Creating and dropping of Views.


1) Create a view that will store employee number ,names, job, salary and department number of all
employees.

CREATE OR REPLACE VIEW EMP1


AS
SELECT EMPNO, ENAME, JOB, SAL, DEPTNO
FROM EMP;
View created.
2) Create a view that will store the information of all employees who are working Dallas.

CREATE OR REPLACE VIEW EMP_DALLAS


AS
SELECT * FROM EMP
WHERE DEPTNO = (SELECT DEPTNO FROM DEPARTMENTS WHERE LOC = ‘DALLAS’);
View created.

3) Drop the view EMP1 that is created from the EMP table.

SQL> DROP VIEW EMP1;


View dropped.

Department of Computer Science and Engineering Page 15


Database Management Systems Lab Manual

WEEK-4
AIM: Queries using Conversion functions (to_char, to_number and to_date), string functions
(Concatenation, lpad, rpad, ltrim, rtrim, lower, upper, initcap, length, substr and instr), date functions
(Sysdate, next_day, add_months, last_day, months_between, least, greatest, trunc, round, to_char, to_date).

a) AIM: Queries using conversion functions (to_char,to_number,to_date)

1) Display the names and hire dates of the employees of deptno 20. Format hire date as ‘12/03/84’.
SQL>SELECT ENAME, TO_CHAR (HIREDATE,’DD/MM/YY’) AS HIREDATE FROM EMP WHERE
DEPTNO=20;
ENAME HIREDATE

SMITH 17/12/80
JONES 02/04/81
SCOTT 19/04/87
ADAMS 23/05/87
FORD 03/12/81
2) Display empno, employee name, job, salary of the employees. Show the salary with thousand
separators.
SQL>SELECT EMPNO, ENAME,JOB,TO_CHAR(SAL,’$9,999’)AS SALARY FROM EMP;
EMPNO ENAME JOB SALARY

7369 SMITH CLERK $800


7499 ALLEN SALESMAN $1,600
7521 WARD SALESMAN $1,250
7566 JONES MANAGER $2,975
7654 MARTIN SALESMAN $1,250
7698 BLAKE MANAGER $2,850
7782 CLARK MANAGER $2,450
7788 SCOTT ANALYST $3,000
7839 KING PRESIDENT $5,000
7844 TURNER SALESMAN $1,500
7876 ADAMS CLERK $1,100
7900 JAMES CLERK $950
7902 FORD ANALYST $3,000
7934 MILLER CLERK $1,300
14 rows selected.
3) List number of employees joined year wise.

SQL> SELECT TO_CHAR(HIREDATE,'YY')AS YY,COUNT(*) FROM EMP GROUP BY


TO_CHAR(HIREDATE,'YY');
YY COUNT(*)

Department of Computer Science and Engineering Page 16


Database Management Systems Lab Manual

80 1
81 10
82 1
87 2
4) List employees who joined between Apr 81 and Apr 82.
SQL> SELECT ENAME,TO_CHAR(HIREDATE,'MON YY') AS HIREDATE FROM EMP WHERE
TO_DATE(HIREDATE) BETWEEN TO_DATE('01-APR-81') AND
TO_DATE('30-APR-82');

ENAME HIREDATE

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.
5)Add ‘100.00’ to the salary of every employee in EMP table
SQL>SELECT ENAME,SAL+TO_NUMBER('100.00') AS SALARY 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
JAMES 1050
FORD 3100
MILLER 1400

14 rows selected.

b) AIM: Queries using string functions


(Concatenation, lpad, rpad, ltrim, rtrim, lower, upper, initcap, length, substr and instr)
Department of Computer Science and Engineering Page 17
Database Management Systems Lab Manual

1) Display the output for all departments in the following manner:


Department number 10 with name Accounting is situated in New York.
SQL> SELECT 'Department number '||DEPTNO||' with name '||INITCAP(DNAME)||' is situated in
'||INITCAP(LOC) AS CONCATENATEDSTRING FROM DEPT;
CONCATENATEDSTRING

Department number 10 with name Accounting is situated in New York


Department number 20 with name Research is situated in Dallas
Department number 30 with name Sales is situated in Chicago
Department number 40 with name Operations is situated in Boston
2) Display ‘*”s before the employee name.
SELECT LPAD (ENAME, 9,’*’) FROM EMP;
LPAD (ENAM

****SMITH
****ALLEN
*****WARD
****JONES
***MARTIN
****BLAKE
****CLARK
****SCOTT
*****KING
***TURNER
****ADAMS
****JAMES
*****FORD
***MILLER
14 rows selected.
3) Display ‘*”s after the employee name.
SELECT RPAD (ENAME, 9,’*’) FROM EMP;
RPAD (ENAM

SMITH****
ALLEN****

Department of Computer Science and Engineering Page 18


Database Management Systems Lab Manual

WARD*****
JONES****
MARTIN***
BLAKE****
CLARK****
SCOTT****
KING*****
TURNER***
ADAMS****
JAMES****
FORD*****
MILLER***
14 rows selected.
4) Left trim of character ‘s’ from employee names of department number 20.
SQL> SELECT LTRIM(ENAME,'S') FROM EMP WHERE DEPTNO=20;
LTRIM(ENAM

MITH
JONES
COTT
ADAMS
FORD
5) Righttrim of character ‘s’ from employee names of department number 20.
SQL> SELECT RTRIM(ENAME,'S') FROM EMP WHERE DEPTNO=20;
RTRIM(ENAM

SMITH
JONE
SCOTT
ADAM
6) List employee names with all capital letters, with all small letters and with first letter only as
capital of department number 10.

Department of Computer Science and Engineering Page 19


Database Management Systems Lab Manual

SQL>SELECT ENAME,UPPER(ENAME),LOWER(ENAME),INITCAP(ENAME) FROM EMP WHERE


DEPTNO=10;
ENAME UPPER(ENAM) LOWER(ENAM INITCAP(EN

CLARK CLARK clark Clark


KING KING king King
MILLER MILLER miller Miller
7) List employee names with length of the name sorted on length for department number 30.
SQL>SELECT ENAME, LENGTH (ENAME) FROM EMP WHERE DEPTNO=30 ORDER BY
LENGTH(ENAME);
ENAME LENGTH(ENAME)

WARD 4
ALLEN 5
BLAKE 5
JAMES 5
MARTIN 6
TURNER 6
6 rows selected.
8) Display the first 4 letters of job of EMP table.
SQL> SELECT DISTINCT(SUBSTR(JOB,1,4)) AS JOB FROM EMP;
JOB

CLER
SALE
MANA
ANAL
PRES
5 rows selected.
9) Display ename and return the position of character ‘S’ in ename.
SQL>SELECT ENAME,INSTR(ENAME,'S') FROM EMP WHERE DEPTNO=20;
ENAME INSTR(ENAME,'S')

Department of Computer Science and Engineering Page 20


Database Management Systems Lab Manual

SMITH 1
JONES 5
SCOTT 1

c) AIM: Queries using date functions.

(Sysdate,next_day,add_months,last_day,months_between,least,greatest,trunk,round,to_char,to_date)

1)List employee names having an experience more than 24 years.


SQL> SELECT ENAME,ROUND(MONTHS_BETWEEN(SYSDATE,HIREDATE)/12) EXP FROM
EMP WHERE ROUND(MONTHS_BETWEEN(SYSDATE,HIREDATE)/12)>24;
ENAME EXP

SMITH 28
ALLEN 28
WARD 28
JONES 28
MARTIN 27
BLAKE 28
CLARK 28
KING 27
TURNER 27
JAMES 27
FORD 27
MILLER 27
12 rows selected.
2) Find the first ‘SUN’day of employees after join in the organization of EMP table.
SQL>SELECT NEXT_DAY (HIREDATE,'SUN') AS HOLIDAY FROM EMP;
HIREDATE HOLIDAY

17-DEC-80 21-DEC-80
20-FEB-81 22-FEB-81
22-FEB-81 01-MAR-81
02-APR-81 05-APR-81

Department of Computer Science and Engineering Page 21


Database Management Systems Lab Manual

28-SEP-81 04-OCT-81
01-MAY-81 03-MAY-81
09-JUN-81 14-JUN-81
19-APR-87 26-APR-87
17-NOV-81 22-NOV-81
08-SEP-81 13-SEP-81
23-MAY-87 24-MAY-87
03-DEC-81 06-DEC-81
03-DEC-81 06-DEC-81
23-JAN-82 24-JAN-82

3) Display hiredate and reviewdate from EMP table, consider reviewdate


As 1year from the hiredate for the deptno ‘20’.
SQL> SELECT HIREDATE,ADD_MONTHS(HIREDATE,12) AS REVIEWDATE FROM EMP WHERE
DEPTNO=20;
HIREDATE REVIEWDAT

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
4) Display last day of joining month of employees of deptno ‘10’ from EMP table.
SQL> SELECT HIREDATE,LAST_DAY(HIREDATE) AS LASTDAY FROM EMP WHERE
DEPTNO=10;
HIREDATE LASTDAY

09-JUN-81 30-JUN-81
17-NOV-81 30-NOV-81
23-JAN-82 31-JAN-82
5) Find the least value of the following series:
9,3,56,89,23,1,0,-2,12,34,9,22

Department of Computer Science and Engineering Page 22


Database Management Systems Lab Manual

SQL> SELECT LEAST(9,3,56,89,23,1,0,-2,12,34,9,22) AS LOWEST FROM DUAL;


LOWEST

-2
6) Find the greatest value of the following series:
9,3,56,89,23,1,0,-2,12,34,9,22
SQL> SELECT GREATEST(9,3,56,89,23,1,0,-2,12,34,9,22) AS HIGHEST FROM DUAL;
HIGHEST

89
7) Trunk of the number 567.231656 by 3.
SQL> SELECT TRUNC(567.231656,3) FROM DUAL;
TRUNC(567.231656,3)

567.231

Department of Computer Science and Engineering Page 23


Database Management Systems Lab Manual

WEEK-5

AIM: a)Create a simple PL/SQL program which includes declaration section, executable section and
exception –Handling section (Ex. Student marks can be selected from the table and printed for those
who secured first class and an exception can be raised if no records were found)

CREATE TABLE STUDENT (ROLLNO NUMBER (10), SNAME VARCHAR2 (10), S1 NUMBER (10),
S2 NUMBER (10), S3 NUMBER (10), S4 NUMBER (10), S5 NUMBER (10), S6 NUMBER (10),
TOTAL NUMBER (10), AVRG NUMBER (7,2), RS VARCHAR2 (10));
Table created.
SQL>SET SERVEROUTPUT ON
SQL>EDIT STUDENT1.SQL
DECLARE
RNO STUDENT.ROLLNO%TYPE;
NAME STUDENT.SNAME%TYPE;
SUB1 STUDENT.S1%TYPE;
SUB2 STUDENT.S2%TYPE;
SUB3 STUDENT.S3%TYPE;
SUB4 STUDENT.S4%TYPE;
SUB5 STUDENT.S5%TYPE;
SUB6 STUDENT.S6%TYPE;
TOT STUDENT.TOTAL%TYPE;
AVRG STUDENT.AVRG%TYPE;
RES STUDENT.RS%TYPE;
BEGIN
RNO:=&ROLLNO;
NAME:='&SNAME';
SUB1:=&S1;
SUB2:=&S2;
SUB3:=&S3;
SUB4:=&S4;
SUB5:=&S5;
SUB6:=&S6;

Department of Computer Science and Engineering Page 24


Database Management Systems Lab Manual

TOT:=SUB1+SUB2+SUB3+SUB4+SUB5+SUB6;
AVRG:=TOT/6;
if((AVRG<=100)AND(AVRG>=70)) then
RES:='DISTINCTION';
DBMS_OUTPUT.PUT_LINE('DISTINCTION');
elsif((AVRG<=69)AND(AVRG>=60)) then
RES:='FIRST CLASS';
DBMS_OUTPUT.PUT_LINE('FIRST CLAASS');
elsif((AVRG<=59)AND(AVRG>=50)) then
RES:='SECOND CLASS';
DBMS_OUTPUT.PUT_LINE('SECOND CLAASS');
elsif((AVRG<=49)AND(AVRG>=35)) then
RES:='THIRD CLASS';
DBMS_OUTPUT.PUT_LINE('THIRD CLAASS');
elsif(AVRG<35) then
RES:='FAIL';
DBMS_OUTPUT.PUT_LINE('FAIL');
end if;
if AVRG>100 then
RAISE_APPLICATION_ERROR(-20001,'NO RECORD FOUND');
end if;
INSERT INTO STUDENT
VALUES(RNO,NAME,SUB1,SUB2,SUB3,SUB4,SUB5,SUB6,TOT,AVRG,RES);
COMMIT;
END;
/
SQL>@ STUDENT1.SQL
Enter value for rollno: 100
old 14: RNO:=&ROLLNO;
new 14: RNO:=100;
Enter value for sname: SMITH
old 15: NAME:='&SNAME';
new 15: NAME:='SMITH';
Department of Computer Science and Engineering Page 25
Database Management Systems Lab Manual

Enter value for s1: 80


old 16: SUB1:=&S1;
new 16: SUB1:=80;
Enter value for s2: 80
old 17: SUB2:=&S2;
new 17: SUB2:=80;
Enter value for s3: 80
old 18: SUB3:=&S3;
new 18: SUB3:=80;
Enter value for s4: 80
old 19: SUB4:=&S4;
new 19: SUB4:=80;
Enter value for s6: 80
old 21: SUB6:=&S6;
new 21: SUB6:=80;DISTINCTION
PL/SQL procedure successfully completed.

b) AIM: Insert data into student table and use COMMIT, ROLLBACK and SAVEPOINT in PL/SQL block.

Create table stu(name varchar(10),branch varchar(10));Insert into


stu values(‘sai’,’it’);
Savepoint h;

Savepoint created

SQL> set serveroutput on;


SQL> begin
savepoint g;
insert into stu values('ruhi','cse');
exception
when dup_val_on_index then
rollback to g;
commit;
end;
/
SQL>Rollback to h;
Rollback completed

Department of Computer Science and Engineering Page 26


Database Management Systems Lab Manual

WEEK-6

AIM: Develop a program that includes the features NESTED IF, CASE and CASE expression. The
program can be extended using the NULLIF and COALESCE functions.

(1) CASE:

Syntax:
Select case("column_name")
when "value1" then "result1"
when "value2" then "result2"
....
[else "resultN"]
end
from "table-name";

program:

select store_name,case store_name


when 'Newyork' then sales*2
when 'chicago' then sales*3
else sales
end
"new
sales"
txn_date
from store_information;

(2) SEARCHED CASE EXPRESSION:

program:

select store_name,txn_date,case
when sales>=8000 then 'congrats get a gift coupon'when
sales>=2000 then 'Thanks for shopping'
else 'Good day'
end
"sales status"
from store_information;

(3) COALESCE:

This returns the first non-NULL expression among its arguements.

Department of Computer Science and Engineering Page 27


Database Management Systems Lab Manual

syntax:
coalesce("expression1","expression2",...);

(4) NULL IF:

Takes two arguements.If the two arguments are equal,then NULL is returned.otherwisethe first
arguement is returned.

syntax:
select column_name,NULLIF(argument1,arguement2) from tabe_name;

(5) PROGRAM FOR CASE:

Declare grade char(1);


begin grade:='a';
case
when grade='a' then
dbms_output.put_line('Excellent');
when grade='b' then
dbms_output.put_line('very good');
when grade='c' then
dbms_output.put_line('good'); when
grade='d' then
dbms_output.put_line('fair');
when grade='f' then
dbms_output.put_line('poor');
else
dbms_output.put_line('No such grade');end
case;
end;
/
;
/

Department of Computer Science and Engineering Page 28


Database Management Systems Lab Manual

WEEK-7
AIM: Program development using WHILE LOOPS, numeric FOR LOOPS, nested loops using ERROR
Handling, BUILT –IN Exceptions, USE defined Exceptions RAISEAPPLICATION ERROR

1) AIM: Addition at run time

Declare
a number;
b
number;c
number;
Begin
a:=&a;
b:=&b;
c:=&c;
dbms_output.put_line('sum of' || a || 'and' || b || 'is' || c);end;
/
output:

Enter value for a: 10


old 6: a:=&a;
new 6: a:=10;
Enter value for b: 10
old 7: b:=&b;
new 7: b:=10;
Enter value for c: 10
old 8: c:=&c;
new 8: c:=10;
sum of10and10is10

PL/SQL procedure successfully completed.

2) AIM: Simple loop to get sum of 100 numbers

Declare
a number;
s1 number default 0;
begin
a:=1;
loop
s1:=s1+a;
exit when(a=100);
a:=a+1;

Department of Computer Science and Engineering Page 29


Database Management Systems Lab Manual

end loop;
dbms_output.put_line('sum between 1 to 100 is' || s1);end;
/
output:

sum between 1 to 100 is5050

PL/SQL procedure successfully completed.

3) AIM: While Loop for sum of 100 odd numbers


Program:
SQL>
declaren
number;
endvalue number; sum1
number default 0;begin
endvalue:=&endvalue;
n:=1;
while(n<endvalue)
loop
sum1:=sum1+n;
n:=n+2;
end loop;
dbms_output.put_line('sum of odd numbers between 1 and ' || endvalue || 'is' || sum1);end;
/
Output:

Enter value for endvalue: 19 old


6: endvalue:=&endvalue;
new 6: endvalue:=19;
sum of odd numbers between 1 and 19 is 81
PL/SQL procedure successfully completed.

4) AIM: if else for finding maximum of three numbers


Program:
SQL>
declarea
number;
b
number;c
number;
begin
a:=&a;
b:=&b;
c:=&c;

Department of Computer Science and Engineering Page 30


Database Management Systems Lab Manual

if(a>b)and(a>c)then
dbms_output.put_line(' a is maximum');
elsif(b>a)and(b>c)then
dbms_output.put_line('b is maximum');else
dbms_output.put_line('c is maximum');end
if;
end;
/

Output:

Enter value for a: 10


old 6: a:=&a;
new 6: a:=10;
Enter value for b: 4
old 7: b:=&b;
new 7: b:=4;
Enter value for c: 19
old 8: c:=&c;
new 8: c:=19;
c is maximum

PL/SQL procedure successfully completed.

5) AIM: select column from table employ by using memory variableProgram:


Declare
Mvsalary number(10,2);
Begin
Select salary into mvsalary
From
Employ
Where ename=’sai’;
Dbms_output.put_line(‘the salary of employ is’ || to_char9mvsalary));End;
/

Output:

The salary of employ is 50000

PL/SQL procedure successfully completed.

Department of Computer Science and Engineering Page 31


Database Management Systems Lab Manual

WEEK-8

AIM: Programs development using creation of procedures, passing parameters IN and OUT of
PROCEDURES.

->create table enquiry(enqno1 number,fname varchar2(30));


->insert into enquiry values(111,'sai');
->insert into enquiry values(112,'sindhu');

/*program*/

create procedure findname(enquiryno1 IN number,fname1 OUT varchar2)is


fname2 varchar2(30);
begin
select fname into fname2
from enquiry
where enqno1=enquiryno1;
fname1:=fname2; exception
when no_data-found then
raise_application_error(-20100,'The given number is not present');
end;
/

/*calling procedure*/

declare
enqno2 number(5);
fname2 varchar2(30);
begin
enqno2:=111;
findname(enqno2,fname2);
dbms_output.put_line(fname2);end;
/
output: sai

Department of Computer Science and Engineering Page 32


Database Management Systems Lab Manual

WEEK-9
AIM: Program development using creation of stored functions, invoke functions in SQL Statements
and write complex functions.

->create table dept(deptno int,dname varchar(10));


->insert into dept values(1219,'sai');

/*program*/

create or replace function getname(dno number)


return varchar2 as
fname1 varchar2(30);
begin
select dname into fname1
from dept
where
deptno=dno;
return(fname);
exception
when no_data_found then
raise_application_error(-20100,'The dno is present');end;
/

/*calling function*/

declare
fname2 varchar2(30);
deptno2 number(5);
begin
deptno:=1219;
fname2:=getname(dno);
dbms_output.put_line(fname2);end;
/
output: sai

Department of Computer Science and Engineering Page 33


Database Management Systems Lab Manual

WEEK-10
AIM: Develop programs using features parameters in a CURSOR, FOR UPDATE CURSOR,
WHERE CURRENT of clause and CURSOR variables.

CURSORS

AIM: create an employ table and retrieve the name of employ whose salary isGreater than
25000 by PL/SQL
Create table employ(eid,ename,salary);

Program:

declare
emp_rec varchar(30);
cursor emp_cur is
select ename
from employ where salary>25000;
Begin
Open emp_cur;
Loop
fetch emp_cur into emp_rec; exit
when emp_rec%notfound;
dbms_output.put_line(emp_rec);end
loop;
close emp_cur;
end;
/

Output:
Sindhu
Sai
Satya
PL/SQL procedure successfully completed.

Department of Computer Science and Engineering Page 34


Database Management Systems Lab Manual

WEEK-11
AIM: Develop Programs using BEFORE and AFTER Triggers, Row and Statement Triggers and
INSTEAD OF Triggers.

SQL> CREATE TABLE CLIENT_MASTER(CLIENTNO VARCHAR2(10),NAME


VARCHAR2(20),BAL_DUE NUMBER(10,2),ADDRESS VARCHAR2(15),CITY
VARCHAR2(20));
Table created.
SQL> CREATE TABLE AUDIT_CLIENT(CLIENTNO VARCHAR2(10),NAME
VARCHAR2(20),BAL_DUE NUMBER(10,2),OPERARTION VARCHAR2(10),USERID
VARCHAR2(10),ODATE DATE);
Table created.
SQL> INSERT INTO CLIENT_MASTER VALUES(1000,'XYZ',50,'SACET','CHIRALA');
1 row created.
SQL> INSERT INTO CLIENT_MASTER VALUES(2000,'ABC',100,'SAEC','CHIRALA');
1 row created.
SQL> SELECT * FROM CLIENT_MASTER;
CLIENTNO NAME BAL_DUE ADDRESS CITY

1000 XYZ 50 SACET CHIRALA


2000 ABC 100 SAEC CHIRALA

SQL> SELECT * FROM AUDIT_CLIENT;


No rows selected.
BEFORE
SQL>EDIT TRIGGER1.SQL
CREATE OR REPLACE TRIGGER AUDIT_TRAIL BEFORE UPDATE ON CLIENT_MASTER FOR
EACH ROW
DECLARE
OPER VARCHAR2(10);
CLIENTNO CLIENT_MASTER.CLIENTNO%TYPE;
NAME CLIENT_MASTER.NAME%TYPE;
BAL_DUE CLIENT_MASTER.BAL_DUE%TYPE;
BEGIN
if UPDATING then
OPER:='UPDATE';

Department of Computer Science and Engineering Page 35


Database Management Systems Lab Manual

end if;
if DELETING then
OPER:='DELETE';
end if;
CLIENTNO:=:OLD.CLIENTNO;
NAME:=:OLD.NAME;
BAL_DUE:=:OLD.BAL_DUE;
INSERT INTO AUDIT_CLIENT
VALUES(CLIENTNO,NAME,BAL_DUE,OPER,USER,SYSDATE);
END;
/
SQL> @ TRIGGER1.SQL
Trigger created.
SQL>UPDATE CLIENT_MASTER SET CLIENTNO=2500 WHERE CLIENTNO=1000;
1 row updated.
SQL> SELECT * FROM CLIENT_MASTER;
CLIENTNO NAME BAL_DUE ADDRESS CITY

2500 XYZ 50 SACET CHIRALA


2000 ABC 100 SAEC CHIRALA

SQL> SELECT * FROM AUDIT_CLIENT;


CLIENTNO NAME BAL_DUE OPERARTION USERID ODATE

1000 XYZ 50 UPDATE SCOTT 20-MAR-09


AFTER
SQL> EDIT TRIGGER2.SQL
CREATE OR REPLACE TRIGGER AUDIT_TRAIL1 AFTER DELETE ON CLIENT_MASTER
FOR EACH ROW
DECLARE
OPER VARCHAR2(10);
CLIENTNO CLIENT_MASTER.CLIENTNO%TYPE;
NAME CLIENT_MASTER.NAME%TYPE;
BAL_DUE CLIENT_MASTER.BAL_DUE%TYPE;
BEGIN

Department of Computer Science and Engineering Page 36


Database Management Systems Lab Manual

if UPDATING then
OPER:='UPDATE';
end if;
if DELETING then
OPER:='DELETE';
end if;
CLIENTNO:=:OLD.CLIENTNO;
NAME:=:OLD.NAME;
BAL_DUE:=:OLD.BAL_DUE;
INSERT INTO AUDIT_CLIENT
VALUES(CLIENTNO,NAME,BAL_DUE,OPER,USER,SYSDATE);
END;
SQL> @ TRIGGER2.SQL
Trigger created.

SQL> DELETE CLIENT_MASTER WHERE CLIENTNO=2000;


1 row deleted.
SQL> SELECT * FROM CLIENT_MASTER;
CLIENTNO NAME BAL_DUE ADDRESS CITY

2500 XYZ 50 SACET CHIRALA


SQL> SELECT * FROM AUDIT_CLIENT;
CLIENTNO NAME BAL_DUE OPERARTION USERID ODATE

2000 ABC 100 DELETE SCOTT 20-MAR-09


1000 XYZ 50 UPDATE SCOTT 20-MAR-09

Department of Computer Science and Engineering Page 37


Database Management Systems Lab Manual

WEEK-12

AIM: Create a table and perform the search operation on table using indexing and non indexing
techniques.
There are two types of indexing in SQL.
1. Clustered index
2. Non-clustered index
1. Clustered – Clustered index is the type of indexing that establishes a physical sorting order of rows.
Suppose you have a table Student_info which contains ROLL_NO as a primary key, then Clustered
index which is self created on that primary key will sort the Student_info table as per ROLL_NO.
Clustered index is like Dictionary; in the dictionary, sorting order is alphabetical and there is no
separate index page.
Examples:
Input:
CREATE TABLE Student_info
(
ROLL_NO int(10) primary key,
NAME varchar(20),
DEPARTMENT varchar(20),
);
insert into Student_info values(1410110405, 'H Agarwal', 'CSE')
insert into Student_info values(1410110404, 'S Samadder', 'CSE')
insert into Student_info values(1410110403, 'MD Irfan', 'CSE')

SELECT * FROM Student_info

Output:
ROLL_NO NAME DEPARTMENT
1410110403MD Irfan CSE
1410110404S SamadderCSE
1410110405H Agarwal CSE

If we want to create a Clustered index on another column, first we have to remove the primary key,
and then we can remove the previous index. Note that defining a column as a primary key makes that
column the Clustered Index of that table. To make any other column, the clustered index, first we have
to remove the previous one as follows below.
Syntax:
//Drop index
drop index table_name.index_name
//Create Clustered index index
create Clustered index IX_table_name_column_name
on table_name (column_name ASC)

Department of Computer Science and Engineering Page 38


Database Management Systems Lab Manual

Non-clustered: Non-Clustered index is an index structure separate from the data stored in a table that
reorders one or more selected columns. The non-clustered index is created to improve the performance
of frequently used queries not covered by a clustered index. It’s like a textbook; the index page is
created separately at the beginning of that book. Examples:
Input:
CREATE TABLE Student_info
(
ROLL_NO int(10),
NAME varchar(20),
DEPARTMENT varchar(20),
);
insert into Student_info values(1410110405, 'H Agarwal', 'CSE')
insert into Student_info values(1410110404, 'S Samadder', 'CSE')
insert into Student_info values(1410110403, 'MD Irfan', 'CSE')

SELECT * FROM Student_info


Output:
ROLL_NO NAME DEPARTMENT
1410110405H Agarwal CSE
1410110404S SamadderCSE
1410110403MD Irfan CSE

Syntax:
//Create Non-Clustered index
create NonClustered index IX_table_name_column_name
on table_name (column_name ASC)
Table: Student_info
ROLL_NO NAME DEPARTMENT
1410110405H Agarwal CSE
1410110404S SamadderCSE
1410110403MD Irfan CSE
Input: create NonClustered index IX_Student_info_NAME on Student_info (NAME
ASC) Output:Index
NAME ROW_ADDRESS
H Agarwal 1
MD Irfan 3
S Samadder2

Department of Computer Science and Engineering Page 39


Database Management Systems Lab Manual

Add-on Programs
1. AIM: Queries on Joins.

Different Types of SQL JOINs


Here are the different types of the JOINs in SQL:
(INNER)JOIN: Returns records that have matching values in both tables.

LEFT(OUTER)JOIN: Return all records from the left table, and the matched records from the right table.

RIGHT(OUTER)JOIN: Return all records from theright table, and the matched records from the left table

FULL (OUTER) JOIN: Return all records when there is a match in either left or right table

SQLINNER JOIN Keyword


The INNER JOIN keyword selects records that have matching values in both tables.

INNER JOIN Syntax


SELECTcolumn_name(s)FROMtable1INNERJOINtable2ONtable1.column_name=
table2.column_name;
INNER JOIN:
SELECTOrders.OrderID,Customers.CustomerName,Orders.OrderDateFROMOrdersIN
NER JOIN Customers ON Orders.CustomerID=Customers.CustomerID;

SQLLEFTJOIN Keyword

Department of Computer Science and Engineering Page 40


Database Management Systems Lab Manual

TheLEFTJOINkeywordreturnsallrecordsfromthelefttable(table1),andthematchedrecordsfrom the
right table (table2).The result is NULLfrom the right side, if there is no match.
LEFTJOIN Syntax
SELECTcolumn_name(s)FROMtable1LEFTJOINtable2ONtable1.column_name=
table2.column_name;

Example
SELECTCustomers.CustomerName,Orders.OrderIDFROMCustomersLEFTJOINOrdersONCustom
ers.CustomerID = Orders.CustomerID ORDER BYCustomers.CustomerName;

SQLRIGHTJOIN Keyword
The RIGHT JOIN keyword returns all records from the right table (table2), and the matched
recordsfrom the left table (table1).The result is NULL from the left side, when there is no match.

RIGHTJOIN Syntax
SELECT column_name(s )FROM table1 RIGHTJOINtable2ONtable1.column_name=

table2.column_name;

Example
SELECTOrders.OrderID,Employees.LastName,Employees.FirstNameFROMOrdersRIGHTJOIN
Employees ON Orders.EmployeeID = Employees.EmployeeID ORDER BY
Orders.OrderID;SQLFULLOUTER JOIN Keyword
TheFULLOUTERJOINkeywordreturnallrecordswhenthereisamatchineitherleft(table1)orright
(table2) table records.

FULLOUTER JOIN Syntax


SELECTcolumn_name(s)FROMtable1FULLOUTERJOINtable2ONtable1.column_name=
table2.column_name;

SQL FULL OUTER JOIN Example


The following SQLstatement selects all customers, and all orders:
SELECTCustomers.CustomerName,Orders.OrderIDFROMCustomersFULLOUTERJOINOrders
ON Customers.CustomerID=Orders.CustomerID ORDER BY Customers.CustomerName;SQLSelf
JOIN
Aself JOIN is a regular join, but the table is joined with itself.
Self JOIN Syntax
SELECTcolumn_name(s) FROM table1 T1, table1 T2 WHERE condition;

Example
SELECT A.CustomerName AS CustomerName1, B.CustomerName AS CustomerName2,
A.CityFROM Customers A, Customers B WHERE A.CustomerID<>B.CustomerID AND A.City
=.CityORDER BYA.City;

Department of Computer Science and Engineering Page 41


Database Management Systems Lab Manual

2 .AIM : Write a PL/SQL Code Bind and Substitution Variables. Printing in PL/SQL.

1. Substitution Variables

The clue here is in the name... "substitution". It relates to values being substituted into the code
before it is submitted to the database.
These substitutions are carried out by the interface being used. In this example we're going to use
SQL*Plus as our interface...
create or replace function myfn return varchar2 is
v_dname varchar2(20);
begin
select dname
into v_dname
from dept
where deptno = &p_deptno;
return v_dname;
end;
Now when this code is submitted...

SQL> /
SQL*Plus, parses the code itself, and sees the "&" indicating a substitution variable.
SQL*Plus, then prompts for a value for that variable, which we enter...
Enter value for p_deptno: 20
old 7: where deptno = &p_deptno;
new 7: where deptno = 20;
and it reports back that it has substituted the &p_deptno variable for the value 20, actually
showing us the whole line of code with it's value.
This code is then submitted to the database. So if we look at what code has been created on the
database we see...
SQL> select dbms_metadata.get_ddl('FUNCTION', 'MYFN', USER) from dual;
DBMS_METADATA.GET_DDL('FUNCTION','MYFN',USER)

CREATE OR REPLACE FUNCTION "SCOTT"."MYFN" return varchar2 is


v_dname varchar2(20);
begin
select dname
into v_dname
from dept
where deptno = 20;

Department of Computer Science and Engineering Page 42


Database Management Systems Lab Manual

return v_dname;
end;
The database itself knows nothing about any substitution variable... it just has some code, fixed
with the value we supplied to SQL*Plus when we compiled it.
The only way we can change that value is by recompiling the code again, and substituting a new
value for it.
Also, with substitution variables we don't necessarily have to use them just for 'values' (though
that it typically what they're used for)... we can use them to substitute any part of the code/text
that we are supplying to be compiled.. e.g.
create or replace function myfn(x in number, y in number) return number is
begin
return &what_do_you_want_to_return;
end;
/
Enter value for what_do_you_want_to_return: y*power(x,2)
old 3: return &what_do_you_want_to_return;
new 3: return y*power(x,2);

Function created.

SQL> select dbms_metadata.get_ddl('FUNCTION', 'MYFN', USER) from dual;


DBMS_METADATA.GET_DDL('FUNCTION','MYFN',USER)

CREATE OR REPLACE FUNCTION "SCOTT"."MYFN" (x in number, y in number)


return number is
begin
return y*power(x,2);
end;

It really does substitute the substitution variable, with whatever text you supply.

2. Bind Variables

Bind variables typically relate to SQL queries (they can be used in dynamic PL/SQL code, but
that's not good practice!), and are a placeholder for values within the query. Unlike substitution
variables, these are not prompted for when you come to compile the code.
Now there are various ways of supplying bind variables, and I'll use a couple of examples, but
there are more (such as binding when creating queries via the DBMS_SQL package etc.)
In the following example:

Department of Computer Science and Engineering Page 43


Database Management Systems Lab Manual

create or replace function myfn(p_deptno in number) return varchar2 is


v_dname varchar2(20);
v_sql varchar2(32767);
begin
v_sql := 'select dname from dept where deptno = :1';
execute immediate v_sql into v_dname using p_deptno;
return v_dname;
end;
/

Function created.
The ":1" is the bind variable in the query.

Department of Computer Science and Engineering Page 44


Database Management Systems Lab Manual

3. AIM: Demonstration of database connectivity

The code below is to help you get started. Copy the code into your JSP directory under
/usr/local/etc/httpd/htdocs/html/LOGIN(whereLOGINisyourloginname).You will need to change the
'xxxxxx' of"con=DriverManager.getConnection("jdbc:mysql://localhost/"+db,user,"xxxxxxx");" to reflect
your MySQL password. Copy the HTML form (right click and view source) to the same directory above
or to your public_html directory and use it connect to your database via the JSPcode. Replace the 'test418'
with your database name and the URL with your JSPURL.

<%@ page import="java.sql.*"%>


<html>
<head>
<title>JDBC Connection example</title>
</head>
<body>
<h1>JDBC Connection example</h1>
<%
String db = request.getParameter("db");
String user = db; // assumes database name is the same as
usernametry {
java.sql.Connection
con;Class.forName("org.gjt.mm.mysql.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost/"+db,user,"xxxx
xxx");out.println (db+ "database successfully opened.");
}
catch(SQLException e) {
out.println("SQLException caught: " +e.getMessage());
}
%>
</body>
</html>

Department of Computer Science and Engineering Page 45

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy