Name Null? Type CUST_NAME VARCHAR2(20) CUST_STREET VARCHAR2(20) CUST_CITY VARCHAR2(20)
Inserting values into customer
insert into customer values('&cust_name','&cust_street','&cust_city');
select * from customer;
CUST_NAME CUST_STREET CUST_CITY anand spring jaipur babu senator hyderabad giri north chennai sreekanth hill delhi shashank main calcutta pradeep alma goa karthik north chennai kishore main calcutta chanu park jaipur saleem putnam stanford 10 rows selected.
Creating loan table VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual 8 Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)
insert into boats values(&bid,'&bcolor','&bname');
select *from boats; VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual 13 Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)
BID BCOLOR BNAME 101 green vamsi 102 white sudeep 103 black giri 104 cream sree 105 red krishna
Queries on Company database
1. Retrieve the names of all employees, who work for research department. Ans: select e.fname,e.lname from employee e,department2 d where e.dept_no=d.dept_no and d.dept_name='research';
FNAME LNAME DEPT_NAME PRASHANTH M RESEARCH
2. For every project located in hyd list the proj_no,dept_no,dept_mgrs last name. Ans: select p.proj_no,p.dept_no,e.lname from project1 p,employee e where p.dept_no=e.dept_no and p.proj_loc='hyd'
PROJ_NO DEPT_NO LNAME 101 11 g 101 11 t 103 12 m
3. Find all employees, who are born in 1950s. Ans: select fname,lname from employee where bdate like '%195_' VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual 14 Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)
FNAME LNAME shashank g Anand m prashanth m
4. Retrieve all employees in dept_no_13 where salary is in between 11000 and 13000. Ans: select fname,lname from employee where dept_no=13 and salary>11000 and salary<13000
FNAME LNAME babu n
5. Retrieve the names of all employees, who dont have supervisors. Ans: select fname,lname from employee where emp_id in(select mgr_id from employee);
FNAME LNAME nano t babu n Anand m
1. Retrieve emp_id of all employees, who work on proj_no=101,105. Ans: select emp_id from works_on where proj_no in(101,105);
EMP_ID 111 116
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual 15 Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)
7.Count the number of distinct salary values in database. Ans: select count(distinct salary) from employee;
COUNT(DISTINCTSALARY) 5
8.For each department retrieve the dept_no and the no. of employees in department and the average salary. Ans: select dept_no,count(*),avg(salary) from employee group by(dept_no);
9.Retrieve the total no. of employees in the company. Ans: select count(emp_id) from employee;
COUNT(EMP_ID) 7
10. Retrieve the total no. of employees in research department. Ans: VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual 16 Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)
select count(*) from employee e,department d where d.dept_no=e.dept_no and d.dept_name='research'
COUNT(*) 1
11.Retrieve the names of employees whose salary>salary of all and employees in dept_no=5. Ans: select fname,lname from employee where salary>all(select salary from employee where dept_no=5);
FNAME LNAME shashank g nano t babu n Anand m sreekanth t prashanth m karthik d 7 rows selected.
Queries on sailors_reserves_boats database
1.Retrieve all sailors information where age less than 19. Ans:
3. Find the names & loan_nos of all customers who have a loan at branch SBI. Ans: select distinct b.loan_no, b.cust_name from borrower b, loan l where b.loan_no=l.loan_no and l.b_name='sb1';
LOAN_NO CUST_NAME 14 sreekanth 17 babu 17 kishore 4. Find the names of all branches that have assets greater than at least one branch located in bangalore Ans: select b_name from branch1 where assets>(select min(assets) from branch1 group by(b_city) having(b_city='banglore'); B_NAME sb3 sb1 sb4 sb7 sb2 sb8 sb5 7 rows selected.
5. Find the names of all customers where street address includes sub string main Ans select distinct cust_name from customer where cust_street like '%main%';
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual 22 Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)
CUST_NAME kishore shashank
6.Find all customers who have a loan at bangalore branch in alphabetical order Ans Select b.cust_name from borrower b, loan l,branch1 b1 where b.loan_no=l.loan_no and b1.b_name=l.b_name and b1.b_city='banglore' order by (b.cust_name);
CUST_NAME anand giri karthik shashank
6.Find all customers having a loan or account or both Ans select cust_name from depositors UNION select cust_name from borrower; CUST_NAME anand babu chanu giri karthik kishore pradeep saleem shashank sreekanth 10 rows selected. 4. Find all customers who have both loan and account VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual 23 Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)
Ans select cust_name from depositors INTERSECT select cust_name from borrower; CUST_NAME karthik kishore shashank
10.Find all customers who have an account but not loan Ans select cust_name from depositors MINUS Select cust_name from borrower; CUST_NAME chanu pradeep saleem 11.Find the average account balance at branch sb3 Ans select avg(balance) from accounts where b_name='sb3'; AVG(BALANCE) 807.5 12.Find the average account balance at each branch Ans select b_name,avg(balance) from accounts group by(b_name); B_NAME AVG(BALANCE) sb1 500 sb2 400 sb3 807.5 sb4 700 sb5 700 sb6 350
13. Find the number of depositors at each branch VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual 24 Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)
Ans select b.b_name,count(d.cust_name) from depositors d,accounts a,branch1 b where b.b_name=a.b_name and a.acc_no=d.acc_no group by b.b_name; B_NAME COUNT(D.CUST_NAME) sb1 1 sb2 1 sb3 2 sb4 1 sb5 1 sb6 1 6 rows selected.
SQL>insert into acc_mstr values ('&acc_no','&type','&operationmode','&opendate',' &currbalance');
ACC_NO TYPE OPERATIONMODE OPENDATE CURRBALANCE B12771 CA Single 12-04-95 2500 VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual 25 Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)
H12902 SB Joint 05-11-00 15000 W87532 SB Single 29-05-04 65000 L35193 CA Single 04-09-90 14500
AVERAGE (AVG()):-
SQL>select avg(currbalance)"Average Balance" from acc_mstr;
Average Balance 24250
MINIMUM (min()):-
SQL>select min(currbalance)"Minimum Balance" from acc_mstr;
Minimum Balance 2500
MAXIMUM (max()):-
SQL>select max(currbalance)"Maximum Balance" from acc_mstr;
Maximum Balance
65000
COUNT():-
SQL>select count(acc_no)"No. of Account" from acc_mstr;
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual 26 Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)
No. of Account 4
COUNT(*):-
SQL>select count(*)"No of Account" from acc_mstr;
No. of Account 4
SUM():-
SQL>select sum(currbalance)"Total Balance" from acc_mstr;
Total Balance
97000
Second Highest
SQL> select max(salary) from emp where salary<(select max(salary) from emp);
Max(salary)
15000
Fifth Highest
SQL> select max(salary) from emp where salary<(select max(salary) from emp where salary<(select max(salary) from emp where salary<(select max(salary) from emp where salary<(select max(salary) from emp))));
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual 27 Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)
SQL>insert into emp values(&emp_no,&ename,&job,&sal,&dept_no);
SQL>select *from emp;
EMP_NO ENAME JOB SAL DEPT_NO 7369 smith clerk 800 20 7499 aleen salesman 1600 30 7566 jones manager 2975 20 7698 blake manager 2800 30 7788 Scott analyst 3000 20 7868 King president 5000 10 7900 James clerk 950 20 7902 Ford analyst 3000 10
IN lists: -
SQL>select ename,job,dept_no from emp where dept_no in(10);
ENAME JOB DEPT_NO King president 10 VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual 30 Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)
Ford analyst 10
NOT IN lists: -
SQL>select ename,job,dept_no from emp where dept_no in(20);
EMP_NO JOB DEPT_NO Allen salesman 30 Blake manager 30 King president 10 Ford annalyst 10
ORDER BY clause:-
SQL>select ename,job,sal, from emp where dept_no(20) order by ename;
EMP_NO JOB SAL James clerk 950 Jones manager 2975 Scott analyst 3000 Smith clerk 800 GROUPBY clause:-
SQL>select dept_no,count(deptno)from emp group by dept_no;
DEPT_NO COUNT(DEPT_NO) 10 2 20 4 30 2
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual 31 Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)
SQL>insert into add_detail values('&code_no','&add1','&add2','&city','&state','&pincode');
SQL>select *from add_detail;
CODE_NO ADD1 ADD2 CITY STATE PINCODE A666 123-21 PT colony Hyd AP 500060 B777 22/12-2 MAGISTIC Bangalore Karnataka 600006 C888 11/23-65 wst-street Vijayawada AP 500015
QUE4)CREATE THE ACCOUNT CUSTOMER DETAILS(acct_fd_cust_detail) TABLE.
SQL>select cust_no"ID",fname||''||lname"Customer|Employee"from cust_mstr,add_detail where cust_mstr.cust_no=add_detail.code_no AND add_detail.city='Hyd' AND add_detail. code_no like'A%' UNION select emp_no"ID",fname ||''||lname "Customer|Employee"from emp_mstr,add_detail where emp_mstr.emp_no=add_detail.code_no AND add_detail.city='Hyd' AND add_detail.code_no like 'A%';
ID CUSYOMER/EMPLOYEE A666 Aaaravi A666 Madhavvenu
INTERSECT CLAUSE: -
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual 35 Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)
SQL>select distinct cust_no from acc_fd_cust_detail where acct_fd_no like 'CA%' OR acct_fd_no 'SB%' INTERSECT select distinct cust_no from acc_fd_cust_detail where acct_fd_no like 'CA%' OR acct_fd_no 'FS%'
CUST_NO CA120
MINUS: -
SQL>select distinct cust_no from acc_fd_cust_detail where acct_fd_no like 'CA%' OR acct_fd_no 'SB%' MINUS select distinct cust_no from acc_fd_cust_detail where acct_fd_no like 'FS%' OR acct_fd_no 'SB%'
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual 39 Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)
10/5 ---------- 2
Numeric Functions:
These functions operate on Numeric data hence is the name. Note: Argument num in the following functions is any float-valued number.
ABS(num): Returns absolute value of the given number.(i.e. Always positive value)
SQL> SELECT ABS(10) FROM DUAL; ABS(10) ---------- 10 SQL> SELECT ABS(-10) FROM DUAL; ABS(-10) ---------- 10
CEIL(num): It returns the smallest integer greater than the given number.
SQL> SELECT CEIL(123.456) FROM DUAL;
CEIL(123.456) ------------- 124
FLOOR(num): It returns the largest integer smaller than the given value. SQL> SELECT FLOOR(123.456) FROM DUAL;
FLOOR(123.456) VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual 40 Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)
-------------- 123
LN(num) : It returns natural logarithm value of num .
SQL> SELECT LN(10) FROM DUAL; LN(10) ---------- 2.30258509
LOG(m, n): It returns logarithm of n with base m.
SQL> SELECT LOG(100,10) FROM DUAL; LOG(100,10) ----------- .5 SQL> SELECT LOG(10,100) FROM DUAL; LOG(10,100) ----------- 2
MOD(m, n) : It returns remainder of m divided by n.
SQL> SELECT MOD(10,3) FROM DUAL; MOD(10,3) ---------- 1
POWER(m, n): It returns value equal to m raised by n.
SQL> SELECT POWER(10,2) FROM DUAL; POWER(10,2) ----------- 100
ROUND(m, n): It rounds the given float-valued number m to the n places after the decimal
SQL> SELECT ROUND(1.23456) FROM DUAL; ROUND(1.23456) -------------- VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual 41 Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)
1 SQL> SELECT ROUND(1.23456,3) FROM DUAL;
ROUND(1.23456,3) ---------------- 1.235
SQRT(m): It calculates square root value of number m
SQL> SELECT SQRT(9) FROM DUAL;
SQRT(9) ---------- 3
TRUNC(m, n): It truncates given float-valued number m to n places after the decimal.
SQL> SELECT TRUNC(1.23456) FROM DUAL; TRUNC(1.23456) -------------- 1 SQL> SELECT TRUNC(1.23456,3) FROM DUAL;
TRUNC(1.23456,3) ---------------- 1.234
GREATEST(expr1, expr2, ) : It finds the greatest value among the given expressions. SQL> SELECT GREATEST(4,7,3,5,9,2) FROM DUAL; GREATEST(4,7,3,5,9,2) --------------------- 9
LEAST(expr1, expr2, ): It finds the Lowest value among the given expressions. SQL> SELECT LEAST(4,7,3,5,9,2) FROM DUAL;
LEAST(4,7,3,5,9,2) ------------------ 2
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual 42 Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)
CHARACTER FUNCTIONS:
UPPER( str) : It converts all letters in the given string str into Upper case.
SQL> SELECT UPPER('abcDEfg') FROM DUAL; UPPER(' ------- ABCDEFG
LOWER(str): It converts all the letters in the given string str into Lower Case.
SQL> SELECT LOWER('ABCDEfg') FROM DUAL; LOWER(' ------- abcdefg
INITCAP(str): It converts first letter of every word VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual 43 Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)
in the given string str into Upper Case and remaining letters into lower case. It is like proper function in FoxPro.
SQL> SELECT INITCAP('ABCDEF') FROM DUAL;
INITCA ------ Abcdef
LENGTH(str) : This function returns the number of characters in the given string (including spaces)
SQL> SELECT LENGTH('ABCD')outpuy FROM DUAL;
LENGTH('ABCD') output -------------- 4
SQL> SELECT LENGTH('AB CD') FROM DUAL;
LENGTH('ABCD') -------------- 5
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual 44 Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)
SUBSTR(str, m, n) : Will extract n characters from the given string starting from m th position.
SQL> SELECT SUBSTR('ABCDEFG',2,3) FROM DUAL SUB --- BCD
SQL> SELECT SUBSTR('ABCDEF',1,3) FROM DUAL SUB --- ABC INSTR(string, str): It displays the location of str in the given string string .
SQL> SELECT INSTR('TRYING TO KEEP THE THINGS AS SIMPLE AS POSSIBLE','AS') FROM DUAL; INSTR(' ----------------------------------------------------- 27
INSTR(string, str, m, n): It displays nth occurrence of str in the string string starting from m.
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual 45 Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)
SQL> SELECT INSTR('TRYING TO KEEP THE THINGS AS SIMPLE AS POSSIBLE','AS',1,2) FROM DUAL INSTR( ------------------------ 37
Note : DUAL IS A TABLE WITH 1 COLUMN AND 1 ROW OF DATA IN IT.
SQL > DESC DUAL Name Null? Type ----------------------------------------- -------- - DUMMY VARCHAR2 (1)
SQL > SELECT * FROM DUAL;
DUMMY ------------ X
LPAD() : This function is used to left pad the given string with specified character or string.
SQL > SELECT LPAD('BCD',4,'A') FROM DUAL;
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual 46 Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)
LPAD ---- ABCD
Explanation: To the given string "BCD" add "A" to the left necessary number of times to make it a string of 4 characters.
SQL > SELECT LPAD('BCD',5,'A') FROM DUAL;
LPAD( ----- AABCD Explanation: To the given string "BCD" add "A" to the left necessary number of times to make it a string of 5 characters.
SQL > SELECT LPAD('BCD',3,'A') FROM DUAL;
LPA --- BCD
Explanation: To the given string "BCD" add "A" to the left necessary number of times to make it a string of 3 characters.
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual 47 Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)
RPAD('BILL', VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual 48 Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)
------------ BILL CLINTON
LTRIM(): This function removes specified string from the given string if it is there to the left of given string.
SQL > SELECT LTRIM('GEORGE BUSH', 'GEORGE') FROM DUAL;
LTRIM ----- BUSH
RTRIM(): This function removes specified string from the given string if it is there to the right of given string.
SQL > SELECT RTRIM('TONY BLAIR', 'AIR') FROM DUAL;
RTRIM(' ------- TONY BL
ASCII(): Displays equivalent ASCII value of a character. SQL > SELECT ASCII('A') FROM DUAL; VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual 49 Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)
ASCII('A') ---------- 65
SQL >SELECT TRANSLATE('JOHN','H','N') FROM DUAL;
TRAN ---- JONN
OTHER FUNCTIONS:
Note: Arguments to the below given functions are in terms of radians
COS(x): It returns the Cosine of x. SQL> SELECT COS(0) FROM DUAL; COS(0) ---------- 1 COSH(x) : It returns hyperbolic cosine of x.
SQL> SELECT COSH(0) FROM DUAL;
COSH(0) ---------- 1
SIN(x) : It returns sine of x.
SQL> SELECT SIN(0) FROM DUAL;
SIN(0) ---------- VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual 50 Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)
0
SINH(x): It returns hyperbolic sine of x.
SQL> SELECT SINH(0) FROM DUAL;
SINH(0) ---------- 0 TAN(x): It returns tangent of x.
SQL> SELECT TAN(0) FROM DUAL;
TAN(0) ---------- 0
TANH(x): It returns hyperbolic tangent of x. SQL> SELECT TANH(0) FROM DUAL;
TANH(0) ---------- 0 DATEFUNCTIONS:
ADD_MONTHS(date, n) : Adds n months to the specified date .
SQL> SELECT ADD_MONTHS('1-JAN-05',5) FROM DUAL; ADD_MONTHS ------------------ 01-JUN-05
LAST_DAY(date): Gives last date of the specified month (date).
SQL> SELECT LAST_DAY('1-JAN-05') FROM DUAL; LAST_DAY( --------- 31-JAN-05
MONTHS_BETWEEN(date1, date2): It gives difference between the two dates date1, date2 in months.
SQL> SELECT MONTHS_BETWEEN('31-DEC-05','1-JAN-05') FROM DUAL VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual 51 Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)
SQL> SELECT TO_DATE('01/01/05', 'DD/MM/YY') FROM DUAL; TO_DATE(' --------- 01-JAN-05
The USER, SYSDATE Functions: USER function displays login name of the user.
SQL> SELECT USER FROM DUAL; VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual 52 Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)
USER ------------------------------ SCOTT
SYSDATE function displays system date.(Date in your windows)
SQL> SELECT SYSDATE FROM DUAL;
SYSDATE --------- 1-JAN-05
CONVERSION FUNCTIONS:
TO_CHAR: This function is used to convert a date or number to character string. SQL> SELECT TO_CHAR(SYSDATE,'DAY DD MONTH YYYY') FROM DUAL
TO_CHAR (SYSDATE,'DAYDDMONTH --------------------------- SATURDAY 01 JANUARY 2005
SQL> SELECT TO_CHAR (SYSDATE,' DD DY MM YY') FROM DUAL;
TO_CHAR (SYSDA ------------- 01 SAT 01 05
NVL() Function: This function is used to substitute any null value with a user-defined value.
Consider the following data from EMP table of SCOTT.
SQL> SELECT EMPNO, ENAME, SAL, COMM FROM EMP;
EMPNO ENAME SAL COMM ---------- ---------- ---------- ------------------------- 7369 SMITH 800 7499 ALLEN 1600 300 VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual 53 Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)
7521 WARD 1250 500 7566 JONES 2975 7654 MARTIN 1250 1400 7698 BLAKE 2850 7782 CLARK 2450 7788 SCOTT 3000 7839 KING 5000 7844 TURNER 1500 0 7876 ADAMS 1100 7900 JAMES 950 7902 FORD 3000 7934 MILLER 1300
In the above table except for 7499, 7521, 7654 and 7844 all others commissions are null To display their commission as 0 (zero)
We can use NVL() function as shown below.
SQL> SELECT EMPNO, ENAME, SAL, NVL (COMM, 100) FROM EMP
EMPNO ENAME SAL NVL(COMM,100) ---------- ---------- ---------- ------------- 7369 SMITH 800 100 7499 ALLEN 1600 300 7521 WARD 1250 500 7566 JONES 2975 100 7654 MARTIN 1250 1400 7698 BLAKE 2850 100 7782 CLARK 2450 100 7788 SCOTT 3000 100 7839 KING 5000 100 7844 TURNER 1500 0 7876 ADAMS 1100 100 7900 JAMES 950 100 7902 FORD 3000 100 7934 MILLER 1300 100
SQL> SELECT EMPNO, ENAME, SAL, NVL (COMM, 888) FROM EMP
EMPNO ENAME SAL NVL(COMM,888) ---------- ---------- ---------- ------------- VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual 54 Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)
7369 SMITH 800 888 7499 ALLEN 1600 300 7521 WARD 1250 500 7566 JONES 2975 888 7654 MARTIN 1250 1400 7698 BLAKE 2850 888 7782 CLARK 2450 888 7788 SCOTT 3000 888 7839 KING 5000 888 7844 TURNER 1500 0 7876 ADAMS 1100 888 7900 JAMES 950 888 7902 FORD 3000 888 7934 MILLER 1300 888
In above queries we have seen how to substitute a value when the comm is null. If one want to display "Commission not payed" against the employees who have no commission we can write the following query.
SQL > SELECT ENAME, SAL, NVL(TO_CHAR(COMM),'Commission Not Payed') FROM EMP; ENAME SAL NVL(TO_CHAR(COMM),'COMMISSIONNOTPAYED') ---------- ---------- ---------------------------------------- SMITH 800 Commission Not Payed ALLEN 1600 300 WARD 1250 500 JONES 2975 Commission Not Payed MARTIN 1250 1400 BLAKE 2850 Commission Not Payed CLARK 2450 Commission Not Payed SCOTT 3000 Commission Not Payed KING 5000 Commission Not Payed TURNER 1500 0 ADAMS 1100 Commission Not Payed JAMES 950 Commission Not Payed FORD 3000 Commission Not Payed MILLER 1300 Commission Not Payed
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual 55 Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)
SUBQUERIES A query nested within a query is known as subquery. For example, you want to see all the employees whose salary is above average salary. For this you have to first compute the average salary using AVG function and then compare employees salaries with this computed salary. This is possible using subquery. Here
the sub query will first compute the average salary and then main query will execute.
Select * from emp where sal > (select avg(sal) from emp);
Similarly we want to see the name and empno of that employee whose salary is maximum.
Select * from emp where sal = (select max(sal) from emp);
To see second maximum salary
Select max(sal) from emp where sal < (select max(sal) from emp);
Similarly to see the Third highest salary.
Select max(sal) from emp where sal < (select max(sal) from emp Where sal < (select max(sal) from emp));
We want to see how many employees are there whose salary is above average.
Select count(*) from emp where sal > (select max(sal) from emp);
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual 56 Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)
We want to see those employees who are working in Hyderabad. Remember emp and dept are joined on deptno and city column is in the dept table. Assuming that wherever the department is located the employee is working in that city.
Select * from emp where deptno in (select deptno from dept where city=HYD);
You can also use subquery in FROM clause of SELECT statement.
For example the following query returns the top 5 salaries from employees table.
Select sal from (select sal from emp order sal desc) where rownum <= 5;
To see the sum salary deptwise you can give the following query.
Select sum(sal) from emp group by deptno;
Now to see the average total salary deptwise you can give a sub query in FROM clause.
select avg(depttotal) from (select sum(sal) as depttotal from emp group by deptno);
WITH
The above average total salary department wise can also be achieved in 9i using WITH clause given below WITH DEPTOT AS (select sum(sal) as dsal from emp group by deptno) select avg(dsal) from deptot;
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual 57 Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)
1) Write a PL/SQL Program to print numbers from 1 to 10.
set serverout on; declare n number(2):=1; begin loop dbms_output.put_line(n); n:=n+1; exit when n>10; end loop; End;
OUTPUT: 1 2 3 4 5 VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual 58 Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)
6 7 8 9 10
2) Write a PL/SQL program to find the AREA OF CIRCLE.
set serverout on; declare pi constant number(4,2):=3.14; radius number(5); area number(14,2); begin radius:=3; while radius<=7 loop area:=pi*power(radius,2); insert into areas values(radius,area); radius:=radius+1; end loop; end;
OUT PUT:-
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual 59 Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)
3) Write a PL/SQL program to find the FIBBONACCI NUMBERS.
set serverout on; declare n number(2):=0; n1 number(2):=1; n2 number(2):=1; begin dbms_output.put_line('fibbonacci series'); dbms_output.put_line(n); dbms_output.put_line(n1); while n2 < 20 loop n2:=n+n1; dbms_output.put_line(n2); n:=n1; n1:=n2; end loop; End;
OUTPUT:- VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual 60 Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)
fibbonacci series 0 1 1 2 3 5 8 13 21
4) Write a PL/SQL program to find the ODD NUMBER.
set serverout on; declare n number(2):=1; begin loop if n mod 2!=0 then dbms_output.put_line(n); exit when n>10; end if; n:=n+1; end loop; End;
OUTPUT:
1 3 5 VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual 61 Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)
7 9 11
5) Write a pl/sql program to display the numbers from 30 to 40.
set serverout on; declare n number(2):=1; begin dbms_output.put_line('enter a number'); n:=&n; dbms_output.put_line('display the numbers from 30 to 40:'); while n <= 40 loop dbms_output.put_line(n); n:=n+1; end loop; end;
Output:-
old 5: n:=&n; new 5: n:=30; enter a number display the numbers from 30 to 40: 30 31 VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual 62 Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)
32 33 34 35 36 37 38 39 40
6) Write a PL/SQL program to find the FACTORIAL OT THE GIVEN NUMBER.
set serverout on; declare num number(10); fact number(10):=1; temp number(10); begin num:=# temp:=num; while num>0 loop fact:=fact*num; num:=num-1; end loop; insert into facto values(temp,fact); end; OUTPUT:-
procedure successfully completed
SQL>select *from facto;
NUM FACT VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual 63 Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)
5 120
7) Write a PL/SQL program to find the given number is PRIME or NOT
set serverout on declare i number:=1; n number(10):=&n; counts number:=0; begin while i<=n loop if n mod i=0 then counts:=counts+1; endif; I:=I+1; End loop; If counts=2 Then dbms_output.put_line(prime); else dbms_output.put_line(not prime); end if; end;
OUT PUT:- old 3: n number(10):=&n; new 3: n number(10):=6; VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual 64 Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)
not prime PL/SQL procedure successfully completed.
Function:-
8) Write a PL/SQL program to find the area of the circle with the function
create function f_cal_area(radius in number) return number is pi constant number(9,7):=3.14; area number(14,2); begin area:=pi*power(radius,2); return area; end;
OUT PUT:-
FUNCTION USING CASE STATEMENTS:
create or replace function Get_Grade1(score IN NUMBER) RETURN VARCHAR2 is begin VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual 65 Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)
CASE
WHEN score BETWEEN 80 AND 100 THEN
dbms_output.put_line('Between 80 and 100'); return 'A';
WHEN score BETWEEN 65 AND 79 THEN dbms_output.put_line('Between 65 and 79'); return 'B';
WHEN score BETWEEN 50 AND 64 THEN dbms_output.put_line('Between 50 and 64'); return 'C';
WHEN score BETWEEN 40 AND 49 THEN dbms_output.put_line('Between 40 and 49'); return 'D';
WHEN score BETWEEN 0 AND 39 THEN dbms_output.put_line('Between 0 and 39'); return 'F';
ELSE return 'Invalid score';
END CASE;
end Get_Grade1;
2. create or replace function Get_Grade2(score IN NUMBER) RETURN VARCHAR2 is grade VARCHAR2(15); begin
grade := CASE WHEN score BETWEEN 80 AND 100 THEN 'A' VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual 66 Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)
WHEN score BETWEEN 65 AND 79 THEN 'B'
WHEN score BETWEEN 50 AND 64 THEN 'C' WHEN score BETWEEN 40 AND 49 THEN 'D' WHEN score BETWEEN 0 AND 39 THEN 'F' ELSE 'Invalid score' END;
return grade;
end Get_Grade2;
Procedure:
create procedure area_c6(radius in number) as pi constant number(9,7):=3.14; area number(14,2); begin area:=pi*power(radius,2); insert into areas values(radius,area); end;
EXCEPTION HANDLING:
1) WRITE A PL/SQL PROGRAM TO DEMONSTRATE THE DIVIDE BY ZERO EXCEPTION
set serveroutput on DECLARE VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual 67 Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)
Num_a NUMBER := 6; Num_b NUMBER; BEGIN Num_b := 0; Num_a := Num_a / Num_b; Num_b := 7; dbms_output.put_line(' Value of Num_b ' || Num_b); EXCEPTION WHEN ZERO_DIVIDE THEN dbms_output.put_line('Trying to divide by zero'); dbms_output.put_line(' Value of Num_a ' || Num_a); bms_output.put_line(' Value of Num_b ' || Num_b); END;
OUT PUT: Trying to divide by zero Value of num_a 6 Value of num_b 0 Pl/sql procedure successfully completed.
2) WRITE A PL/SQL PROGRAM TO DEMONSTRATE THE STRING CONVERSION EXCEPTION
CREATE TABLE EMPLOYEE(NUM NUMBER); BEGIN INSERT INTO EMPLOYEE(NUM ) VALUES(123X); EXCEPTION VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual 68 Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)
WHEN INVALID_NUMBER THEN DBMS_OUTPUT.PUT_LINE (CONVERSION TO STRING TO NUMBER FAILED); END;
O/P: CONVERSION TO STRING TO NUMBER FAILED PL/SQL PROCEDURE SUCCESFULLY COMPLETED.
Triggers:-
A trigger is a pl/sql block structure which is fired when a DML statements like Insert, Delete, Update is executed on a database table. A trigger is triggered automatically when an associated DML statement is executed. Syntax of Triggers The Syntax for creating a trigger is: CREATE [OR REPLACE ] TRIGGER trigger_name {BEFORE | AFTER | INSTEAD OF } {INSERT [OR] | UPDATE [OR] | DELETE} [OF col_name] ON table_name [REFERENCING OLD AS o NEW AS n] VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual 69 Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)
[FOR EACH ROW] WHEN (condition) BEGIN --- sql statements END; CREATE [OR REPLACE ] TRIGGER trigger_name - This clause creates a trigger with the given name or overwrites an existing trigger with the same name. {BEFORE | AFTER | INSTEAD OF } - This clause indicates at what time should the trigger get fired. i.e for example: before or after updating a table. INSTEAD OF is used to create a trigger on a view. before and after cannot be used to create a trigger on a view. {INSERT [OR] | UPDATE [OR] | DELETE} - This clause determines the triggering event. More than one triggering events can be used together separated by OR keyword. The trigger gets fired at all the specified triggering event. [OF col_name] - This clause is used with update triggers. This clause is used when you want to trigger an event only when a specific column is updated. CREATE [OR REPLACE ] TRIGGER trigger_name - This clause creates a trigger with the given name or overwrites an existing trigger with the same name. [ON table_name] - This clause identifies the name of the table or view to which the trigger is associated. [REFERENCING OLD AS o NEW AS n] - This clause is used to reference the old and new values of the data being changed. By default, you reference the values as :old.column_name or :new.column_name. The reference names can also be changed from old (or new) to any other user-defined name. You cannot reference old values when inserting a record, or new values when deleting a record, because they do not exist. [FOR EACH ROW] - This clause is used to determine whether a trigger must fire when each row gets affected ( i.e. a Row Level Trigger) or just once when the entire sql statement is executed(i.e.statement level Trigger). WHEN (condition) - This clause is valid only for row level triggers. The trigger is fired only for rows that satisfy the condition specified. For Example: The price of a product changes constantly. It is important to maintain the history of the prices of the products. We can create a trigger to update the 'product_price_history' table when the price of the product is updated in the 'product' table. 1) Create the 'product' table and 'product_price_history' table VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual 70 Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)
2) Create the price_history_trigger and execute it.
CREATE or REPLACE TRIGGER price_history_trigger BEFORE UPDATE OF unit_price ON product FOR EACH ROW BEGIN INSERT INTO product_price_history VALUES (:old.product_id, :old.product_name, :old.supplier_name, :old.unit_price); END;
3) Lets update the price of a product. VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual 71 Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)
UPDATE PRODUCT SET unit_price = 800 WHERE product_id = 100 Once the above update query is executed, the trigger fires and updates the 'product_price_history' table.
4)If you ROLLBACK the transaction before committing to the database, the data inserted to the table is also rolled back.
Types of PL/SQL Triggers
There are two types of triggers based on the which level it is triggered. 1) Row level trigger - An event is triggered for each row upated, inserted or deleted. 2) Statement level trigger - An event is triggered for each sql statement executed.
PL/SQL Trigger Execution Hierarchy
The following hierarchy is followed when a trigger is fired. 1) BEFORE statement trigger fires first. 2) Next BEFORE row level trigger fires, once for each row affected. 3) Then AFTER row level trigger fires once for each affected row. These events will alternates between BEFORE and AFTER row level triggers. 4) Finally the AFTER statement level trigger fires.
For Example: Let's create a table 'product_check' which we can use to store messages when triggers are fired. VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual 72 Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)
Let's create a BEFORE and AFTER statement and row level triggers for the product table.
1. BEFORE UPDATE, Statement Level: This trigger will insert a record into the table 'product_check' before an sql update statement is executed, at the statement level.
CREATE or REPLACE TRIGGER Before_Update_Stat_product BEFORE UPDATE ON product Begin INSERT INTO product_check Values('Before update, statement level',sysdate); END;
2) BEFORE UPDATE, Row Level: This trigger will insert a record into the table 'product_check' before each row is updated.
CREATE or REPLACE TRIGGER Before_Upddate_Row_product BEFORE UPDATE ON product FOR EACH ROW VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual 73 Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)
BEGIN INSERT INTO product_check Values('Before update row level',sysdate); END;
3) AFTER UPDATE, Statement Level: This trigger will insert a record into the table 'product_check' after a sql update statement is executed, at the statement level.
CREATE or REPLACE TRIGGER After_Update_Stat_product AFTER UPDATE ON product BEGIN INSERT INTO product_check Values('After update, statement level', sysdate); End;
4) AFTER UPDATE, Row Level: This trigger will insert a record into the table 'product_check' after each row is updated.
CREATE or REPLACE TRIGGER After_Update_Row_product AFTER insert On product FOR EACH ROW BEGIN INSERT INTO product_check VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual 74 Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)
Values('After update, Row level',sysdate); END; /
Now lets execute a update statement on table product.
UPDATE PRODUCT SET unit_price = 800 WHERE product_id in (100,101);
Lets check the data in 'product_check' table to see the order in which the trigger is fired.
SELECT * FROM product_check; Output: Mesage Current_Date ------------------------------------------------------------ Before update, statement level 26-Nov-2008 Before update, row level 26-Nov-2008 After update, Row level 26-Nov-2008 Before update, row level 26-Nov-2008 After update, Row level 26-Nov-2008 After update, statement level 26-Nov-2008
The above result shows 'before update' and 'after update' row level events have occured twice, since two records were updated. But 'before update' and 'after update' statement level events are fired only once per sql statement. The above rules apply similarly for INSERT and DELETE statements.
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual 75 Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)
How to know information about Triggers.
We can use the data dictionary view 'USER_TRIGGERS' to obtain information about any trigger.
The below statement shows the structure of the view 'USER_TRIGGERS'
DESC USER_TRIGGERS; NAME Type -------------------------------------------------------- TRIGGER_NAME VARCHAR2(30) TRIGGER_TYPE VARCHAR2(16) TRIGGER_EVENT VARCHAR2(75) TABLE_OWNER VARCHAR2(30) BASE_OBJECT_TYPE VARCHAR2(16) TABLE_NAME VARCHAR2(30) COLUMN_NAME VARCHAR2(4000) REFERENCING_NAMES VARCHAR2(128) WHEN_CLAUSE VARCHAR2(4000) STATUS VARCHAR2(8) DESCRIPTION VARCHAR2(4000) ACTION_TYPE VARCHAR2(11) TRIGGER_BODY LONG This view stores information about header and body of the trigger.
SELECT * FROM user_triggers WHERE trigger_name = 'Before_Update_Stat_product';
The above sql query provides the header and body of the trigger 'Before_Update_Stat_product'.
You can drop a trigger using the following command. VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual 76 Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)