Dbms r20 Lab Manual Final
Dbms r20 Lab Manual Final
II B.TECH I SEM
Lab Manual
Regulation: R20
INTERNATIONAL SCHOOL OF TECHNOLOGY & SCIENCES
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
Add-on Programs
WEEK-1
AIM: Creation, altering and dropping of tables and inserting rows into a table (use constraints while
creating tables) examples using SELECT command.
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 SALGRADE (GRADE NUMBER (1), LOSAL NUMBER (4), HISAL NUMBER
(4));
Table created.
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.
EMP
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
SALGRADE
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);
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;
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
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;
ENAME SAL
JONES 2975
BLAKE 2850
CLARK 2450
SCOTT 3000
FORD 3000
6) List employee names in alphabetical order.
ENAME
ADAMS
ALLEN
BLAKE
CLARK
FORD
JAMES
JONES
KING
MARTIN
MILLER
SCOTT
SMITH
TURNER
WARD
14 rows selected.
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.
JOB
ANALYST
CLERK
MANAGER
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
SCOTT 3000
KING 5000
ALLEN
WARD
MARTIN
BLAKE
TURNER
JAMES
6 rows selected.
SMITH
JONES
CLARK
SCOTT
KING
ADAMS
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.
ENAME
SMITH
JONES
CLARK
SCOTT
KING
ADAMS
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
SQL> SELECT DEPTNO FROM DEPT MINUS SELECT DEPTNO FROM EMP;
DEPTN
40
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
14
29025
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');
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;
20 5
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
3) Drop the view EMP1 that is created from the EMP table.
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).
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
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.
****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****
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.
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')
SMITH 1
JONES 5
SCOTT 1
(Sysdate,next_day,add_months,last_day,months_between,least,greatest,trunk,round,to_char,to_date)
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
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
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
-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
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;
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
b) AIM: Insert data into student table and use COMMIT, ROLLBACK and SAVEPOINT in PL/SQL block.
Savepoint created
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:
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:
syntax:
coalesce("expression1","expression2",...);
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;
WEEK-7
AIM: Program development using WHILE LOOPS, numeric FOR LOOPS, nested loops using ERROR
Handling, BUILT –IN Exceptions, USE defined Exceptions RAISEAPPLICATION ERROR
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:
Declare
a number;
s1 number default 0;
begin
a:=1;
loop
s1:=s1+a;
exit when(a=100);
a:=a+1;
end loop;
dbms_output.put_line('sum between 1 to 100 is' || s1);end;
/
output:
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:
Output:
WEEK-8
AIM: Programs development using creation of procedures, passing parameters IN and OUT of
PROCEDURES.
/*program*/
/*calling procedure*/
declare
enqno2 number(5);
fname2 varchar2(30);
begin
enqno2:=111;
findname(enqno2,fname2);
dbms_output.put_line(fname2);end;
/
output: sai
WEEK-9
AIM: Program development using creation of stored functions, invoke functions in SQL Statements
and write complex functions.
/*program*/
/*calling function*/
declare
fname2 varchar2(30);
deptno2 number(5);
begin
deptno:=1219;
fname2:=getname(dno);
dbms_output.put_line(fname2);end;
/
output: sai
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.
WEEK-11
AIM: Develop Programs using BEFORE and AFTER Triggers, Row and Statement Triggers and
INSTEAD OF Triggers.
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
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.
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')
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)
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')
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
Add-on Programs
1. AIM: Queries on Joins.
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
SQLLEFTJOIN Keyword
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.
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;
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)
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.
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:
Function created.
The ":1" is the bind variable in the query.
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.