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

Dbms Lab Workbook Mca

gbnm,

Uploaded by

Roja
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Dbms Lab Workbook Mca

gbnm,

Uploaded by

Roja
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 52

SQL> CREATE TABLE emp (

empno decimal(4,0) NOT NULL,


ename varchar(10) default NULL,
job varchar(9) default NULL,
mgr decimal(4,0) default NULL,
hiredate date default NULL,
sal decimal(7,2) default NULL,
comm decimal(7,2) default NULL,
deptno decimal(2,0) default NULL
);

To check the table has been created


SQL> DESC emp;

SQL> CREATE TABLE dept (


deptno decimal(2,0) default NULL,
dname varchar(14) default NULL,
loc varchar(13) default NULL
);

SQL> DESC dept;

SQL> INSERT INTO emp VALUES (7369,'SMITH','CLERK',7902,'17-DEC-1980’,800.00,NULL,20);


INSERT INTO emp VALUES (7499,'ALLEN','SALESMAN',7698,'20-FEB-1981’, 1600.00, 300.00, 30);
INSERT INTO emp VALUES ('7521','WARD','SALESMAN',7698,'1981-02-22',1250.00,500.00,30);
INSERT INTO emp VALUES ('7566','JONES','MANAGER',7839,'1981-04-02',2975.00,NULL,20);
INSERT INTO emp VALUES ('7654','MARTIN','SALESMAN',7698,'1981-09-28',1250.00,1400.00, 30);
INSERT INTO emp VALUES ('7698','BLAKE','MANAGER',7839,'1981-05-01',2850.00,NULL,30);
INSERT INTO emp VALUES ('7782','CLARK','MANAGER',7839,'1981-06-09',2450.00,NULL,10);
INSERT INTO emp VALUES ('7788','SCOTT','ANALYST',7566,'1982-12-09',3000.00,NULL,20);
INSERT INTO emp VALUES ('7839','KING','PRESIDENT',NULL,'1981-11-17',5000.00,NULL,10);
INSERT INTO emp VALUES ('7844','TURNER','SALESMAN',7698,'1981-09-08',1500.00,0.00,30);
INSERT INTO emp VALUES ('7876','ADAMS','CLERK',7788,'1983-01-12',1100.00,NULL,20);
INSERT INTO emp VALUES ('7900','JAMES','CLERK',7698,'1981-12-03',950.00,NULL,30);
INSERT INTO emp VALUES ('7902','FORD','ANALYST',7566,'1981-12-03',3000.00,NULL,20);
INSERT INTO emp VALUES ('7934','MILLER','CLERK',7782,'1982-01-23',1300.00,NULL,10);

SQL> INSERT INTO dept VALUES (10,'ACCOUNTING','NEW YORK');


INSERT INTO dept VALUES (20,'RESEARCH','DALLAS');
INSERT INTO dept VALUES (30,'SALES','CHICAGO');
INSERT INTO dept VALUES (40,'OPERATIONS','BOSTON');

SQL> commit;

To list all records from the table


SQL> select * from emp;

SQL> select * from dept;

K.NARESH DBMS LAB MANUAL/WORKBOOK Page 1


SQL SELECT statement is used to query or retrieve data from a table in the database. A query may retrieve
information from specified columns or from all of the columns in the table. To create a simple SQL SELECT
Statement, you must specify the column(s) name and the table name. The whole query is called SQL SELECT
Statement.

Syntax of SQL SELECT Statement:

SELECT column_list FROM table-name


[WHERE Clause <condition>]
[GROUP BY clause <column-name(s)>]
[HAVING clause <condition>]
[ORDER BY clause<expression>];

 table-name is the name of the table from which the information is retrieved.
 column_list includes one or more columns from which data is retrieved.
 The code within the brackets is optional.

1. To list all information about all employees from emp table


SELECT * FROM emp;

2. List all information about all departments from dept table


SELECT * FROM dept;

3. List all employee names along with their salaries from emp table
SELECT ename, sal FROM emp;

K.NARESH DBMS LAB MANUAL/WORKBOOK Page 2


4. List all department numbers, employee numbers and their manager’s numbers in that order from emp
table.
SELECT deptno, empno, mgr FROM emp;

5. List department names and locations from the dept table.


SELECT dname, loc FROM dept;

Assignment:
1. Write an SQL statement to retrieve empno, comm. and hiredate from emp table.

Conditional Retrieval
Conditional retrieval enables selective rows to be selected. Although selecting rows, restriction can be applied
by a condition which governs the selection. F
urther clause called WHERE must be provided along with the SELECT statement to apply the condition to
select a specific set of rows. The order of prior first goes to the WHERE clause and the records that match the
condition are alone selected.

Syntax:
Select (column name(s)) FROM (table name(s)) WHERE condition(s)

1. Use comparison operators in a WHERE clause to select different subsets of data.

The following table lists the comparison operators that you can use:

Relational or Comparison Operators

Symbol Mnemonic Definition Example


Equivalent

= EQ equal to where Name = 'Asia';

^= or ~= or ¬= or NE not equal to where Name ne 'Africa';


<>

> GT greater than where Area > 10000;

< LT less than where Depth < 5000;

>= GE greater than or equal to where Statehood >= '01jan1860'd;

<= LE less than or equal to where Population <= 5000000;

2. Use many different conditional operators in a WHERE clause. The following table lists other operators that
you can use:

Special Conditional Operators

Operator Definition Example

ANY specifies that at least one of a set of where Population > any (select Population
values obtained from a subquery must from sql.countries)
satisfy a given condition

ALL specifies that all of the values obtained where Population > all (select Population from
from a subquery must satisfy a given sql.countries)
condition

K.NARESH DBMS LAB MANUAL/WORKBOOK Page 3


BETWEEN-AND tests for values within an inclusive where Population between 1000000 and
range 5000000

CONTAINS tests for values that contain a specified where Continent contains 'America';
string

EXISTS tests for the existence of a set of values where exists (select * from sql.oilprod);
obtained from a subquery

IN tests for values that match one of a list where Name in ('Africa', 'Asia');
of values

IS NULL or IS tests for missing values where Population is missing;


MISSING

LIKE tests for values that match a specified where Continent like 'A%';
pattern (table note 1)

=* tests for values that sound like a where Name =* 'Tiland';


specified value
TABLE NOTE 1: You can use a percent symbol (%) to match any number of characters. You can use an

underscore (_) to match one arbitrary character.

All of these operators can be prefixed with the NOT operator to form a negative condition.

The IN operator enables to include values within a list that you supply.

The IS MISSING operator enables to identify rows that contain columns with missing values.

To select rows based on a range of values, you can use the BETWEEN-AND operators. Because the
BETWEEN-AND operators are inclusive, the values that you specify in the BETWEEN -AND expression are
included

The LIKE operator enables you to select rows based on pattern matching.

3. Logical Operators: AND, OR, NOT

1. List the employees belonging to the department 20


SELECT * FROM emp WHERE deptno = 20;

2. List the name and salary of the employees whose salary is more than 1000
SELECT ename, sal FROM emp WHERE sal > 1000;

3. List employee number and name of managers


SELECT empno, ename FROM emp where job = ‘MANAGER’;

4. List the names of the clerks working in the department 20


SELECT ename FROM emp WHERE job = ‘CLERK’ AND deptno = 20;

5. List the names of analysts and salesmen


SELECT ename FROM emp WHERE job = ‘SALESMAN’ OR job = ‘ANALYST’;

6. List the details of the employees who have joined before the end of September 1981
SELECT * FROM emp WHERE hiredate <= ’30-SEP-1981’;

K.NARESH DBMS LAB MANUAL/WORKBOOK Page 4


7. List the name of employees who are not managers
SELECT ename FROM emp WHERE job <> ‘MANAGER’;

8. List the name of the employees whose employee numbers are 7369, 7521, 7839, 7934, 7788
SELECT ename FROM emp WHERE empno = 7369 OR empno = 7521 OR empno = 7839 OR empno = 7934
OR empno = 7788;

 The Special Operators IN and BETWEEN can be used in place of complex relational or logical operators

SELECT ename FROM emp WHERE empno IN (7369, 7521, 7839, 7934, 7788);

9. List the employee details not belonging to the department 10, 30 and 40
SELECT * FROM emp WHERE deptno NOT IN (10, 30, 40);

10. List the employee name and salary, whose salary is between 1000 and 2000
SELECT ename, sal FROM emp WHERE sal BETWEEEN 1000 AND 2000;

11. List employee names who have joined before 30 th June 1981 and after December1981
SELECT ename FROM emp WHERE hiredate NOT BETWEEN ’30-JUN-1981’ AND ’31-DEC-1981’;

DISTINCT clause with SELECT


Used with SELECT to suppress duplicate values if any in a column

12. List the different jobs (designations) available in emp table


SELECT DISTINCT job FROM emp;

Working with null values:


Null values are not 0 or blank. It represents an unknown or inapplicable value. It cannot be compared using
the relational and/or logical operators. The special operator ‘IS’ is used with the keyword ‘NULL’ to locate
NULL values.

13. List the employee names who are not eligible for commission
SELECT ename FROM emp WHERE comm IS NULL;

14. List the name of the employee and job of the employee who does not report to anybody (managers is
NULL)
SELECT ename, job FROM emp WHERE mgr IS NULL;

15. List the employees not assigned to any department


SELECT ename FROM emp WHERE deptno IS NULL;

16. List the employees who are eligible for commission


SELECT ename FROM emp WHERE comm IS NOT NULL;

17. List the details of employees whose salary is greater than 2000 and commission is null.
SELECT * FROM emp WHERE sal > 2000 AND comm IS NULL;

Matching a pattern with a column from a table

The LIKE operator is used only with CHAR and VARCHAR2 to match a pattern.
‘%’ represents a sequence of zero or more characters
‘_’ underscore stands for any single character

K.NARESH DBMS LAB MANUAL/WORKBOOK Page 5


Both ‘%’ and ‘_’ are wildcard characters and are used with the LIKE operator to specify a pattern

18. List the employees whose names start with an “S”


SELECT ename FROM emp WHERE ename LIKE ‘S%’;

19. List the employees whose names ending with “S”


SELECT ename FROM emp WHERE ename LIKE ‘ %S’;

20. List the names of employees whose names have exactly 5 characters
SELECT ename FROM emp WHERE ename LIKE ‘ ’;

21. List the employee names having ‘I’ as the second character
SELECT ename FROM emp WHERE ename LIKE ‘_I’;

Using Expressions with columns


Arithmetic computations can be done on numeric columns
Alias names can be given to columns and/or expressions on query outputs
Alias names are displayed in place of column names
Alias names are given to the right of a column name, enclosed within quotes

22. List the name, salary and PF amount of all the employees (PF is calculated as 10% of salary)
SELECT ename, sal, sal * .1 FROM emp;
or
SELECT ename, sal, sal * .1 as “PF” FROM emp;

23. List the names of employees who are more than 25 years old in the organization
SELECT ename FROM emp WHERE (SYSDATE – hiredate) > ( 25 * 365);

SYSDATE is a pseudo column representing the system date

DUAL table is owned by the user ‘SYS’ and can be accessed by all users. It contains one DUMMY column and
one row with a value X. It is useful to return a value once only.

Ordering the Results of a Query


SQL uses the ORDER BY clause to impose an order on the result of a query in SELECT Statement.
It sorts the query output according to the values in one or more selected columns.
Multiple columns are ordered one within another and the user can specify whether to order them in
ascending (default) or descending order.
It must always be the last statement in the statement.

24. List the empno, ename, sal in ascending order of salary


SELECT empno, ename, sal FROM emp ORDER BY sal;

25. List the empno, ename, sal, hiredate in descending order of hiredate.
SELECT empno, ename, sal, hiredate FROM emp ORDER BY hiredate DESC;

26. List the employee name, Salary, job and department no. in ascending order of deptno and then on
descending order of salary
SELECT deptno, job, ename, sal FROM emp ORDER BY deptno, sal desc;

Ordering output by column number

27. List the employee details in ascending order of salary

K.NARESH DBMS LAB MANUAL/WORKBOOK Page 6


SELECT empno, ename, sal FROM emp ORDER BY 3;

28. List the employee name, salary, PF, HRA, DA and gross; order the result in ascending order of gross. HRA
is 50% of salary and DA is 30% of salary
SELECT ename, sal, sal * .1 “PF”, sal * .5 “HRA”, sal * .3 “DA”, sal + (sal * .5) + (sal * .3) – (sal * .1) “GROSS”
FROM emp ORDER BY 6;

AGGREGATE FUNCTIONS

The aggregate functions produce a single value for an entire group or table

NULLs are ignored in all the aggregate functions.

COUNT(*| [Distinct ] | ALL | column name ) - Determines the number of rows or non-NULL column
values. If * is passed, then the total number of rows is returned.

29. List the number of employees working with the company


SELECT COUNT(*) FROM emp;

30. List the number of jobs available in the emp table


SELECT COUNT(DISTINCT job) FROM emp;

SUM([DISTINCT | ALL] column name) – Determines the sum of all selected columns

31. List the total salaries payable to employees


SELECT SUM(sal) FROM emp;

MAX(column name) – Returns the maximum value of the selected list of item.

32. List the maximum salary of employees working as a salesman


SELECT MAX(sal) FROM emp WHERE job = ‘SALESMAN’;

MIN(column name) – Returns the minimum value of the selected list of item.

33. List the minimum salary from emp table


SELECT MIN(sal) FROM emp;
AVG ( [DISTINCT | ALL] column name ) – returns the average of column values

34. List the average salary and number of employees working in the department 20
SELECT AVG (sal), COUNT (*) FROM emp WHERE deptno = 20;

Grouping the Result of a query

GROUP BY clause is used with SELECT to combine a group of rows based on the values of a particular
column or expression. Aggregate functions are used to return summary information for each group. The
aggregate functions are applied to the individual groups.

The WHERE clause is used to conditionally retrieve rows from a table, hence it cannot be applied to grouped
result.

The HAVING clause is used only with the expressions and/or columns that are specified with the GROUP BY
clause.

K.NARESH DBMS LAB MANUAL/WORKBOOK Page 7


35. List the deptno(s) and number of employees in each department
SELECT deptno, COUNT (*) FROM emp GROUP BY deptno;

36. List the department number and the total salary payable in each department
SELECT deptno, SUM(sal) FROM emp GROUP BY deptno;

37. List the jobs and the number of employees in each job. The result should be in descending order of the
number of employees:
SELECT job, COUNT(*) FROM emp GROUP BY job ORDER BY job DESC;

38. List the total salary, maximum, minimum and the average salary of employees job wise
SELECT job, SUM(sal), AVG(sal), MAX(sal), MIN(sal) FROM emp GROUP BY job;

39. List the average salary from each job excluding managers
SELECT job, AVG(sal) FROM emp WHERE job <> ‘MANAGER’ GROUP BY job;
SELECT job, AVG(sal) FROM emp WHERE job = ‘MANAGER’ ;

40. List the total salary, maximum, minimum and the average salary of employees job-wise, for department
number 20 only
SELECT job, SUM(sal), AVG(sal), MAX(sal), MIN(sal) FROM emp WHERE deptno = 20 GROUP BY job;

Groups within groups GROUP BY clause can be used to provide results for groups within groups

41. List the average salary for each job type within department
SELECT deptno, job, AVG (sal) FROM emp GROUP BY deptno, job;

HAVING clause is used to specify which groups are to be displayed, i.e., restricts the groups that return on
the basis of aggregate functions

42. List average salary for all departments employing more than five people
SELECT deptno, AVG(sal) FROM emp GROUP BY deptno HAVING COUNT (*) > 5
43. List jobs of all the employees where maximum salary is >= 5000
SELECT job, MAX(sal) FROM emp GROUP BY job HAVNG MAX(SAL) >= 5000;

44. List the total salary, maximum, minimum and the average salary of employees jobwise, for department
number 20 only and display only those rows having average salary greater than 1000
SELECT job, SUM(sal), AVG(sal), MAX(sal), MIN(sal) FROM emp WHERE deptno = 20 GROUP BY job HAVING
AVG(sal) > 1000;

45. For the above query, the output should be arranged in the ascending order of SUM(sal)
SELECT job, SUM(sal), AVG(sal), MAX(sal), MIN(sal) FROM emp WHERE deptno = 20 GROUP BY job HAVING
AVG(sal) > 1000 ORDER BY SUM(sal);

46. List the deptno(s) and names in department name order.


47. List the details of employees in departments 10 and 20 in alphabetical order of name
48. List names and jobs of all clerks in department 20 in alphabetical order of name
49. List the names of all employees who have LL and LT in their names
50. List names and total remuneration for all employees
51. List name, annual salary and commission of all salespeople whose monthly salary is greater than their
commission, the output should be ordered by salary, highest first. If two or more employees have the same
salary sort by employee name within the highest salary order
52. List lowest paid employees working for each manager, sort the output by salary

K.NARESH DBMS LAB MANUAL/WORKBOOK Page 8


QUERYING MULTIPLE TABLES

SQL joins are used to combine rows from two or more tables.

The join clause is used to combine tables based on a common column and a join condition.
An equi join is a type of join that combines tables based on matching values in specified columns.
Please remember that:
 The column names do not need to be the same.
 The resultant table contains repeated columns.
 It is possible to perform an equi join on more than two tables.

There are two ways to use equi join in SQL:


SELECT *
FROM TableName1, TableName2
WHERE TableName1.ColumnName = TableName2.ColumnName;

OR

SELECT *
FROM TableName1
JOIN TableName2
ON TableName1.ColumnName = TableName2.ColumnName;

Note: Equijoins are also called simple joins or inner joins.

1. To retrieve records with Equijoins


SELECT EMP.EMPNO, EMP.ENAME, EMP.DEPTNO,
DEPT.DEPTNO, DEPT.LOC
FROM EMP, DEPT
WHERE EMP.DEPTNO = DEPT.DEPTNO;

2. To retrieve records with Equijoins using Table aliases


SELECT e.empno, e.ename, e.deptno,
d.deptno, d.loc
FROM emp e, dept d
WHERE e.deptno = d.deptno;

3. To display King's employee number, name, department number, and departments location.
SELECT EMP.EMPNO, EMP.ENAME, EMP.DEPTNO,
DEPT.DEPTNO, DEPT.LOC
FROM EMP, DEPT
WHERE EMP.DEPTNO = DEPT.DEPTNO
AND INITCAP(ename) = 'King' ;

The most common type of join is: SQL INNER JOIN (simple join).
An SQL INNER JOIN returns all rows from multiple tables where the join condition is met.

The types of the different SQL JOINs are:


 INNER JOIN: Returns all rows when there is at least one match in BOTH tables
 LEFT JOIN: Return all rows from the left table, and the matched rows from the right table
 RIGHT JOIN: Return all rows from the right table, and the matched rows from the left table
 FULL JOIN: Return all rows when there is a match in ONE of the tables

K.NARESH DBMS LAB MANUAL/WORKBOOK Page 9


The INNER JOIN keyword selects all rows from both tables as long as there is a match between the columns
in both tables. This joins are also called as equi-joins.
Syntax
SELECT column_name(s) FROM table1 INNER JOIN table2 ON table1.column_name = table2.column_name;
or:
SELECT column_name(s) FROM table1 JOIN table2 ON table1.column_name=table2.column_name;
Note: INNER JOIN is the same as JOIN.

1. List the employee numbers, names, department numbers and the department name
SELECT emp.empno, emp.ename, emp.deptno, dept.dname FROM emp, dept
WHERE emp.deptno = dept.deptno;

2. List the employee numbers, names, department numbers and the department name using table aliases
(effectively speeds up the query)
SELECT e.empno, e.ename, e.deptno, d.dname FROM emp e, dept d WHERE e.deptno = d.deptno;

3. SELECT e.job, d.loc


FROM emp e , dept d
WHERE e.deptno = d.deptno
AND e.deptno = 30;

4. SELECT e.ename, d.dname, d.loc


FROM emp e , dept d
WHERE comm IS NOT NULL
AND e.deptno = d.deptno ;

The LEFT JOIN keyword returns all rows from the left table (table1), with the matching rows in the right table
(table2). The result is NULL in the right side when there is no match.
Note: The INNER JOIN keyword selects all rows from both tables as long as there is a match between the
columns.
Syntax
SELECT column_name(s) FROM table1 LEFT JOIN table2 ON table1.column_name = table2.column_name;
or:
SELECT column_name(s) FROM table1LEFT OUTER JOIN table2 ON table1.column_name =
table2.column_name;
PS! In some databases LEFT JOIN is called LEFT OUTER JOIN.

The RIGHT JOIN keyword returns all rows from the right table (table2), with the matching rows in the left
table (table1). The result is NULL in the left side when there is no match.

K.NARESH DBMS LAB MANUAL/WORKBOOK Page 10


Note: The LEFT JOIN keyword returns all the rows from the left table, even if there are no matches in the
right table.
Syntax
SELECT column_name(s) FROM table1
RIGHT JOIN table2
ON table1.column_name=table2.column_name;
or:
SELECT column_name(s) FROM table1
RIGHT OUTER JOIN table2
ON table1.column_name=table2.column_name;

PS! In some databases RIGHT JOIN is called RIGHT OUTER JOIN.

Note: The RIGHT JOIN keyword returns all the rows from the right table, even if there are no matches in the
left table.

The FULL OUTER JOIN keyword returns all rows from the left table (table1) and from the right table (table2).
The FULL OUTER JOIN keyword combines the result of both LEFT and RIGHT joins.
Syntax
SELECT column_name(s) FROM table1 FULL OUTER JOIN table2
ON table1.column_name=table2.column_name;

Note: The FULL OUTER JOIN keyword returns all the rows from the left table and all the rows from the right
table. If there are rows in table1 that do not have matches in table2, or if there are rows in table2 that do not
have matches in table1 those rows will be listed as well.

Outer join operator is the plus sign (+).

SELECT tablel.column, table2. column


FROM tablel, table2
WHERE tablel.column(+) = table2.column;

SELECT tablel.column, table2.column


FROM tablel, table2
WHERE tablel.column. = table2. column {+) ;

5. Query to illustrate outer join


SELECT e.ename, d.DEPTNO, d.dname
FROM emp e, dept d
WHERE e.deptno(+) = d.deptno

K.NARESH DBMS LAB MANUAL/WORKBOOK Page 11


ORDER BY e.deptno;

CARTESIAN JOINS
When no join condition clause is specified in WHERE clause, each row of one table matches every row of
another table. This results in a Cartesian Product.

6. SELECT empno, ename, dname, loc FROM emp, dept;

SELF JOIN
To join a table to itself means that each row of the table is combined with itself and with every other row of
the table. It can be viewed as a join of two copies of the same table.

7. List all the employees who joined the company before their manager
SELECT e.ename, e.hiredate, m. ename manager, m.hiredate FROM emp e, emp m
WHERE e.mgr = m.empno and e.hiredate < m.hiredate;

8. Query to illustrate self-join


SELECT e.ename, e.empno , m.ename, m.empno
FROM emp e, emp m
WHERE e.mgr = m.empno;

SET OPERATORS

The SQL UNION Operator


The UNION operator is used to combine the result-set of two or more SELECT statements.
Notice that each SELECT statement within the UNION must have the same number of columns. The columns
must also have similar data types. Also, the columns in each SELECT statement must be in the same order.
Syntax
SELECT column_name(s) FROM table1
UNION
SELECT column_name(s) FROM table2;

9. Display the different designations in department 20 and 30


SELECT job FROM emp WHERE deptno = 20
UNION
SELECT job FROM emp WHERE deptno = 30 ;

10. Display empno, ename from emp where deptno is 10 and 30 in ascending order of empno
SELECT empno, ename FROM emp WHERE deptno = 10
UNION
SELECT empno, ename FROM emp WHERE deptno = 30
ORDER BY 1;

Note: The UNION operator selects only distinct values by default. To allow duplicate values, use the ALL
keyword with UNION.

SQL UNION ALL Syntax


SELECT column_name(s) FROM table1
UNION ALL
SELECT column_name(s) FROM table2;
PS: The column names in the result-set of a UNION are usually equal to the column names in the first
SELECT statement in the UNION.

K.NARESH DBMS LAB MANUAL/WORKBOOK Page 12


SELECT INTO
The SELECT INTO statement copies data from one table and inserts it into a new table.
Syntax
We can copy all columns into the new table:

SELECT * INTO newtable [IN externaldb] FROM table1;

Or we can copy only the columns we want into the new table:

SELECT column_name(s) INTO newtable [IN externaldb] FROM table1;

The new table will be created with the column-names and types as defined in the SELECT statement. You can
apply new names using the AS clause.

SELECT empno, deptno INTO t_emp FROM emp;

INTERSECT Operator
Returns the rows that are common between two sets of rows

Syntax
SELECT column_name(s) FROM table1
INTERSECT
SELECT column_name(s) FROM table2;

11. List the jobs common to department 20 and 30


SELECT job FROM emp WHERE deptno=20
INTERSECT
SELECT job FROM emp WHERE deptno=30;

MINUS Operator
Returns the rows unique to first query

Syntax
SELECT column_name(s) FROM table1
MINUS
SELECT column_name(s) FROM table2;

12. List the jobs unique to department 20


SELECT job FROM emp WHERE deptno = 20 MINUS SELECT job FROM emp WHERE deptno = 10 MINUS
SELECT job FROM emp WHERE deptno = 30;

OR

SELECT job FROM emp WHERE deptno = 20 MINUS


SELECT job FROM emp WHERE deptno IN (10,30);

K.NARESH DBMS LAB MANUAL/WORKBOOK Page 13


NESTED QUERIES

A Subquery or Inner query or Nested query is a query within another SQL query and embedded within the
WHERE clause.
A subquery is used to return data that will be used in the main query as a condition to further restrict the
data to be retrieved.
Subqueries can be used with the SELECT, INSERT, UPDATE, and DELETE statements along with the
operators like =, <, >, >=, <=, IN, BETWEEN etc.
There are a few rules that subqueries must follow:
 Subqueries must be enclosed within parentheses.
 A subquery can have only one column in the SELECT clause, unless multiple columns are in the main
query for the subquery to compare its selected columns.
 An ORDER BY cannot be used in a subquery, although the main query can use an ORDER BY. The
GROUP BY can be used to perform the same function as the ORDER BY in a subquery.
 Subqueries that return more than one row can only be used with multiple value operators, such as the IN
operator.
 The SELECT list cannot include any references to values that evaluate to a BLOB, ARRAY, CLOB, or
NCLOB.
 A subquery cannot be immediately enclosed in a set function.
 The BETWEEN operator cannot be used with a subquery; however, the BETWEEN operator can be used
within the subquery.

Subqueries with the SELECT Statement:

Subqueries are most frequently used with the SELECT statement. The basic syntax is as follows:

SELECT column_name [, column_name ] FROM table1 [, table2 ]


WHERE column_name OPERATOR (SELECT column_name [, column_name ]
FROM table1 [, table2 ] [WHERE] )

13. List the employees belonging to the department of MILLER


SELECT ename FROM emp WHERE deptno = (SELECT deptno FROM emp WHERE ename = ‘MILLER’);

Using aggregate functions in Subqueries


14. List the name of employee who draws the highest salary
SELECT ename FROM emp WHERE sal = (SELECT MAX(sal) FROM emp);

15. List all employee details of an employee whose salary is greater than the average salary of employees
whose hiredate is before ’01-APR-1981’
SELECT * FROM emp WHERE
sal > (SELECT AVG(sal) FROM emp WHERE hiredate < ‘01-APR-1981’’);

Subqueries in Having clause


16. List the job with highest average salary
SELECT job, AVG (sal) FROM emp GROUP BY job HAVING AVG (sal) = (SELECT MAX (AVG( sal )) FROM emp
GROUP BY job);

Distinct Clause with Subqueries


17. Find the details of the department whose manager’s empno is 7698
SELECT * FROM dept
WHERE deptno = (SELECT DISTINCT deptno FROM emp WHERE mgr = 7698);

Subqueries that return more than one row

K.NARESH DBMS LAB MANUAL/WORKBOOK Page 14


Use Multirow return Operators

18. List the names of the employees who earn lowest salary in each department
SELECT ename, deptno FROM emp
WHERE sal IN (SELECT MIN(sal) FROM emp GROUP BY deptno);

A correlated subquery is a SQL query that depends on values executed by an outer query in order to
complete.

Because a correlated subquery requires the outer query to be executed first, the correlated subquery must
run once for every row in the outer query. This causes correlated subqueries to be less efficient than other
subqueries.

A correlated subquery is a nested subquery which is executed once for each ‘candidate row’ considered by the
main query and which on execution uses a value from a column in the outer query.

In a correlated subquery, the column value used in inner sub query refers to the column value represent in
the outer query forming a correlated subquery. The subquery is executed repeatedly, once for each row of the
main (outer) query table.

19. List employee details who earn salary greater than the average salary
SELECT empno, ename, sal, deptno FROM emp e
WHERE sal > (SELECT AVG(sal) FROM emp);

Using Special Operators in Subqueries


1. EXISTS
This operator is used to check the existence of values. It produces Boolean result. It takes as an argument
and evaluates it to true if the subquery produces any output and false, if the subquery does not produces any
output
NOT EXISTS operator is used when the subquery returns any null values.

20. List all employees who have atleast one person reporting to them
SELECT empno, ename, job, deptno FROM emp e
WHERE EXISTS (SELECT empno FROM emp WHERE emp.mgr = e.empno);

21. List the employee details iff more than 2 employees are present in deptno 10
SELECT * FROM emp WHERE deptno = 10 AND EXISTS
(SELECT COUNT(*) FROM emp WHERE deptno = 10 GROUP BY deptno HAVING COUNT(*) > 2);

22. List all the employee details who do not manage any one
SELECT ename, job FROM emp e WHERE NOT EXISTS
(SELECT mgr FROM emp WHERE mgr = e.empno);

2. ANY operator - This compares the lowest value from the set. Used along with the relational operators.

23. List the employee names whose salary is greater than the lowest salary of an employee belonging to
deptno 20
SELECT ename FROM emp WHERE sal > ANY (SELECT sal FROM emp WHERE deptno = 20);

24. List the employee details of those employees whose salary is greater than any of the managers
SELECT empno, ename, sal FROM emp WHERE sal > ANY
(SELECT sal FROM emp WHERE job = ‘MANAGER’);

K.NARESH DBMS LAB MANUAL/WORKBOOK Page 15


3. ALL operator –The predicate is true if every value selected by the subquery satisifies the condition in the
predicate of the outer query

25. List the employee names whose salary is greater than the highest salary of all employee belonging to dept
20
SELECT ename FROM emp WHERE sal > ALL (SELECT sal FROM emp WHERE deptno = 20);

26. List the employee details of those employees whose salary is more than the highest paid manager
SELECT empno, ename, sal FROM emp
WHERE sal > ALL(SELECT sal FROM emp WHERE job = ‘MANAGER’);

Hands on Session
1. List all employees, their job and deptno, who are having same job as that of any employee of deptno 20
2. Using self join, list all the employees who have joined before their manager
3. List all employees who earn less than the average salary of all the employees
4. List all employees name along with their manager’s name.
5. Also list the name of employee who has no manager
6. Display the dept that has no employee
7. List the employee details who earn minimum salary for their job
8. List the ename, sal, deptno for those employees who earn sal greater than the avg sal of their dept. Sort
the output in deptno order
9. List the employee details who earn highest salary for their job
10. List the details of those employees who are among the five highest earners of the company

K.NARESH DBMS LAB MANUAL/WORKBOOK Page 16


DATA MANIPULATION AND CONTROL

Creating Tables
Tables are created using the CREATE TABLE command. Tables are owned by the user who creates them. The
names of tables owned by a given user must be unique. The column names in the table must be unique.
Column names can be duplicated across tables.

Tables can be created at any time. Table structure can also be modified. Specifying table name is compulsory
while creating a table.

Syntax for creating table is:


CREATE TABLE table_name
(
column_name1 data_type(size), column_name2 data_type(size), column_name3 data_type(size),
.... );

The column_name parameters specify the names of the columns of the table.
The data_type parameter specifies what type of data the column can hold (e.g. varchar, integer, decimal, date,
etc.).
The size parameter specifies the maximum length of the column of the table.

Create table ITEMMAST, which has the following columns:

Column Name Type Size Description


ITNO Number 4 Item Number
NAME Varchar2 20 Item Description
QOH Number 5 Quantity on Hand
CLASS Character 1 Category of Item
UOM Character 4 Unit of Measurement
ROL Number 5 Reorder Level
ROQ Number 5 Reorder Quantity
RATE Number 8,2 Unit Price of Sale

K.NARESH DBMS LAB MANUAL/WORKBOOK Page 17


SQL Constraints
SQL constraints are used to specify rules for the data in a table.
If there is any violation between the constraint and the data action, the action is aborted by the constraint.
Constraints can be specified when the table is created (inside the CREATE TABLE statement) or after the
table is created (inside the ALTER TABLE statement).

SQL CREATE TABLE + CONSTRAINT Syntax


CREATE TABLE table_name
(
column_name1 data_type(size) constraint_name,
column_name2 data_type(size) constraint_name,
column_name3 data_type(size) constraint_name,
....
);
In SQL, we have the following constraints:
 NOT NULL - Indicates that a column cannot store NULL value
 UNIQUE - Ensures that each row for a column must have a unique value
 PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Ensures that a column (or combination of
two or more columns) have a unique identity which helps to find a particular record in a table more easily
and quickly
 FOREIGN KEY - Ensure the referential integrity of the data in one table to match values in another table
 CHECK - Ensures that the value in a column meets a specific condition
 DEFAULT - Specifies a default value for a column

By default, a table column can hold NULL values.

Constraints can be defined in two ways:


1) The constraints can be specified immediately after the column definition. This is called column-level
definition.
2) The constraints can be specified after all the columns are defined. This is called table-level definition.

SQL NOT NULL Constraint


The NOT NULL constraint enforces a column to NOT accept NULL values.
The NOT NULL constraint enforces a field to always contain a value. This means that you cannot insert a new
record, or update a record without adding a value to this field.

CREATE TABLE itemmast(


ITNO NUMBER(4), NAME VARCHAR2(20), QOH NUMBER(5), CLASS CHAR(1), UOM CHAR(4), ROL
NUMBER(5) NOT NULL, ROQ NUMBER(5) NOT NULL, RATE NUMBER(8,2) NOT NULL);

SQL UNIQUE Constraint


The UNIQUE constraint uniquely identifies each record in a database table.

CREATE TABLE itemmast1(


ITNO NUMBER(4) NOT NULL CONSTRAINT IT_UN UNIQUE,
NAME VARCHAR2(20) NOT NULL CONSTRAINT IT_NA UNIQUE,
QOH NUMBER(5),
CLASS CHAR(1),
UOM CHAR(4),
ROL NUMBER(5) NOT NULL,
ROQ NUMBER(5) NOT NULL,
RATE NUMBER(8,2) NOT NULL);

Or

K.NARESH DBMS LAB MANUAL/WORKBOOK Page 18


CREATE TABLE itemmast2(
ITNO NUMBER(4) NOT NULL,
NAME VARCHAR2(20) NOT NULL,
QOH NUMBER(5),
CLASS CHAR(1),
UOM CHAR(4),
ROL NUMBER(5) NOT NULL,
ROQ NUMBER(5) NOT NULL,
RATE NUMBER(8,2) NOT NULL,
UNIQUE(ITNO, NAME) );

The UNIQUE and PRIMARY KEY constraints both provide a guarantee for uniqueness for a column or set of
columns.

A PRIMARY KEY constraint automatically has a UNIQUE constraint defined on it.


Note that you can have many UNIQUE constraints per table, but only one PRIMARY KEY constraint per table.

CREATE TABLE itemmast4(


ITNO NUMBER(4) PRIMARY KEY,
NAME VARCHAR2(20) , QOH NUMBER(5), CLASS CHAR(1), UOM CHAR(4), ROL NUMBER(5) NOT NULL, ROQ
NUMBER(5) NOT NULL, RATE NUMBER(8,2) NOT NULL);

If we require to declare the combination of ITNO and NAME as Primary Key, then this can be defined as:
CREATE TABLE itemmast5(
ITNO NUMBER(4), NAME VARCHAR2(20), QOH NUMBER(5), CLASS CHAR(1), UOM CHAR(4), ROL
NUMBER(5) NOT NULL, ROQ NUMBER(5) NOT NULL, RATE NUMBER(8,2) NOT NULL,
PRIMARY KEY(ITNO, NAME));

CHECK Constraint: Specific condition is specified, which must evaluate to true for constraint to be satisfied.

CREATE TABLE itemmast6(


ITNO NUMBER(4) PRIMARY KEY,
NAME VARCHAR2(20) NOT NULL,
QOH NUMBER(5),
CLASS CHAR(1) CHECK (CLASS IN (‘A’, ‘B’, ‘C’) ) ,
UOM CHAR(4),
ROL NUMBER(5) CHECK (ROL > 0),
ROQ NUMBER(5) CHECK (ROQ > 0),
RATE NUMBER(8,2) NOT NULL);

CREATE TABLE itemmast(


ITNO NUMBER(4) PRIMARY KEY,
NAME VARCHAR2(20) NOT NULL,
QOH NUMBER(5),
CLASS CHAR(1) NOT NULL, UOM CHAR(4), ROL NUMBER(5) NOT NULL, ROQ NUMBER(5) NOT NULL, RATE
NUMBER(8,2) NOT NULL,
CHECK ( ( ( CLASS = ‘A’ AND RATE < 1000) OR (CLASS = ‘B’ AND RATE > 1000 AND RATE <4500) OR (CLASS
= ‘C’ AND RATE > 4500) AND (ROL > 0 AND ROQ > 0) ) );

SQL DEFAULT Constraint is used to insert a default value into a column. The default value will be added to
all new records, if no other value is specified.

Eg. To have 100 as QoH for every item,

K.NARESH DBMS LAB MANUAL/WORKBOOK Page 19


CREATE TABLE itemmast(
ITNO NUMBER(4) PRIMARY KEY,
NAME VARCHAR2(20) NOT NULL,
QOH NUMBER(5) DEFAULT 100,
CLASS CHAR(1) NOT NULL, UOM CHAR(4), ROL NUMBER(5) NOT NULL, ROQ NUMBER(5) NOT NULL, RATE
NUMBER(8,2) NOT NULL,
CHECK ( ( ( CLASS = ‘A’ AND RATE < 1000) OR (CLASS = ‘B’ AND RATE > 1000 AND RATE <4500) OR (CLASS
= ‘C’ AND RATE > 4500) AND (ROL > 0 AND ROQ > 0) ) );

SQL FOREIGN KEY Constraint - REFERENCES


A FOREIGN KEY in one table points to a PRIMARY KEY in another table.
The FOREIGN KEY constraint is used to prevent actions that would destroy links between tables.
The FOREIGN KEY constraint also prevents invalid data from being inserted into the foreign key column,
because it has to be one of the values contained in the table it points to. This constraint is also known as
relationship (referential) constraints. FOREIGN KEY constraint applied column must have same data type as
the reference on another table column.
Integrity Constraints are used to apply business rules for the database tables.

To create an item transaction table with referential integrity

Create table ITTRAN, which has the following columns:


Column Name NULL? Type Size Description
ITNO REFERENCES ITEMMAST(itno) Number 4 Item Number
TRANTYPE CHECK(trantype IN (‘I’,’R’) ) CHAR 1 Transaction Type
TRANDATE Date Transaction Date
QTY Number 5 Quantity

CREATE TABLE ittran(


itno NUMBER(4) REFERENCES ITEMMAST(itno),
trantype CHAR(1) CHECK (trantype IN (‘I’,’R’)),
trandate DATE,
qty NUMBER(5));

ON DELETE CASCADE option

Using this option whenever a parent row is deleted then all the corresponding child rows are deleted from the
child table. This option is always used with the foreign key.

CREATE TABLE ittran(


itno NUMBER(4) REFERENCES ITEMMAST(itno) ON DELETE CASCADE,
trantype CHAR(1) CHECK (trantype IN (‘I’,’R’)),
trandate DATE,
qty NUMBER(5));

Creating a Table with Rows from Another Table

Syntax is:
CREATE TABLE tablename [ (column name, ……, ….) ] AS SELECT statement;

 The table will be created with the specified columns and the rows retrieved by the SELECT statement
inserted into it.
 If all the columns in the SELECT statement have well-defined names, the column specifications may be
omitted

K.NARESH DBMS LAB MANUAL/WORKBOOK Page 20


 If column specifications are given, the number of columns must equal the number of items in the SELECT
list
 Constraints information is inherited from the selected table
 Data type for the column cannot be specified

1. Create a table EMP2 from EMP table having employee number, name, job, manager, salary of employees
from department 10 and 20.
CREATE TABLE emp2 AS
SELECT empno, ename, job, mgr, sal FROM emp WHERE deptno IN (10, 20);

2. Create a table SALARY from EMP table having ename and salary
CREATE TABLE salary (Name, Salary) AS SELECT ename, sal FROM emp;

Inserting Values into a table


INSERT command is used to insert rows into table.
Values can be inserted for all the columns or for the selected columns.
Character and date data will be enclosed within quotes.

Syntax;
INSERT INTO table_name VALUES(<list-of-values>);

1. Single row or record insertion:


INSERT INTO emp VALUES(7311,’TIMOTHY’,’CLERK’,7001,’18-APR-95’,3000,NULL,20);

2. To insert only the empno, name and sal, then


INSERT INTO emp (empno, ename, sal) VALUES(8234,’SAMUEL’, 6000);

Inserting through Parameter substitution


INSERT INTO emp VALUES(&1,’&2’,’&3’,&4,’&5’,&6, NULL,&7);

INSERT INTO emp VALUES(&empno,’&ename’,’&job’,&mgr,’&hiredate’,&sal,&comm,&deptno);

Updating Column(s) of a Table


UPDATE command is used to update the columns in a table.
Values of a single or a group of columns can be updated.
Updates can be carried out for all the rows in a table or selected rows.
It sets specific values for each column required to change.
The UPDATE Statement is used to modify the existing rows in a table.

Syntax:
UPDATE table_name SET column_name1 = value1, column_name2 = value2, ... [WHERE condition]
 table_name - the table name which has to be updated.
 column_name1, column_name2.. - the columns that gets changed.
 value1, value2... - are the new values.

NOTE: In the Update statement, WHERE clause identifies the rows that get affected. If you do not include the
WHERE clause, column values for all the rows get affected.

1. To increase everyone’s salary by 40%


UPDATE emp SET sal = sal + (sal * 0.4);

2. Change the department of King to 40

K.NARESH DBMS LAB MANUAL/WORKBOOK Page 21


UPDATE emp SET deptno = 40 WHERE ename = ‘KING’;

3. All employees who have more than 2 people reporting to them, are to directly report to the PRESIDENT
UPDATE emp SET mgr = 7839 WHERE mgr <> 7839 AND empno IN (SELECT mgr FROM emp GROUP BY mgr
HAVING COUNT (*) > 2);

Deleting rows from a table


DELETE command is used to delete one or more rows from a table. WHERE clause allows a set of rows to be
deleted which follows the condition.
The entire row is deleted from the table.
Specific columns cannot be deleted from a table.
CASCADE Delete rule instructs DBMS to automatically set the foreign key values to null in the child rows, if
the parent row is deleted. The delete thus cascades from the parent to the child.

Syntax:
DELETE FROM <tablename> [WHERE <condition>]

1. Delete all records from emp


DELETE FROM emp;

2. Delete the records of clerks


DELETE FROM emp WHERE job = ‘CLERK’;

Dropping Columns
ALTER TABLE command removes the column from the table description and removes the column length and
data from each row of the table.

ALTER TABLE <tablename> DROP COLUMN <columnname>;

If there are any unused columns in the table i.e., without data can also be removed using
ALTER TABLE <tablename> DROP UNUSED COLUMNS;

SQL PRIMARY KEY Constraint on ALTER TABLE


To create a PRIMARY KEY constraint on the "P_Id" column when the table is already created, use the following
SQL:

ALTER TABLE Persons ADD PRIMARY KEY (P_Id)


To allow naming of a PRIMARY KEY constraint, and for defining a PRIMARY KEY constraint on multiple
columns, use the following SQL syntax:

ADD CONSTRAINT pk_PersonID PRIMARY KEY (P_Id, LastName)


Note: If you use the ALTER TABLE statement to add a primary key, the primary key column(s) must already
have been declared to not contain NULL values (when the table was first created).

To DROP a PRIMARY KEY Constraint


To drop a PRIMARY KEY constraint, use the following SQL:
Eg. ALTER TABLE Persons DROP PRIMARY KEY
Eg. ALTER TABLE Persons DROP CONSTRAINT pk_PersonID

SQL FOREIGN KEY Constraint on CREATE TABLE


The following SQL creates a FOREIGN KEY on the "P_Id" column when the "Orders" table is created:
CREATE TABLE Orders
(

K.NARESH DBMS LAB MANUAL/WORKBOOK Page 22


O_Id int NOT NULL, OrderNo int NOT NULL, P_Id int,
PRIMARY KEY (O_Id),
FOREIGN KEY (P_Id) REFERENCES Persons(P_Id)
)

SQL FOREIGN KEY Constraint on ALTER TABLE


To create a FOREIGN KEY constraint on the "P_Id" column when the "Orders" table is already created, use the
following SQL:
Eg. ALTER TABLE Orders ADD FOREIGN KEY (P_Id) REFERENCES Persons(P_Id)

To allow naming of a FOREIGN KEY constraint, and for defining a FOREIGN KEY constraint on multiple
columns, use the following SQL syntax:
Eg. ALTER TABLE Orders ADD CONSTRAINT fk_PerOrders FOREIGN KEY (P_Id) REFERENCES Persons(P_Id)

To DROP a FOREIGN KEY Constraint


To drop a FOREIGN KEY constraint, use the following SQL:
ALTER TABLE Orders DROP FOREIGN KEY fk_PerOrders
ALTER TABLE Orders DROP CONSTRAINT fk_PerOrders

SQL CHECK Constraint on ALTER TABLE


To create a CHECK constraint on the "P_Id" column when the table is already created, use the following SQL:
ALTER TABLE Persons ADD CHECK (P_Id>0)

To allow naming of a CHECK constraint, and for defining a CHECK constraint on multiple columns, use the
following SQL syntax:
ALTER TABLE Persons ADD CONSTRAINT chk_Person CHECK (P_Id>0 AND City='Sandnes')

To DROP a CHECK Constraint


To drop a CHECK constraint, use the following SQL:
ALTER TABLE Persons DROP CONSTRAINT chk_Person

SQL DEFAULT Constraint on ALTER TABLE


To create a DEFAULT constraint on the "City" column when the table is already created, use the following
SQL:
Eg. ALTER TABLE Persons MODIFY City DEFAULT 'SANDNES'

To DROP a DEFAULT Constraint


To drop a DEFAULT constraint, use the following SQL:
Eg. ALTER TABLE Persons ALTER COLUMN City DROP DEFAULT

The DROP TABLE Statement


The DROP TABLE statement is used to delete a table.
DROP TABLE table_name

The DEFAULT constraint can also be used to insert system values, by using functions like GETDATE():
CREATE TABLE Orders
(
O_Id int NOT NULL,
OrderNo int NOT NULL,
P_Id int,
OrderDate date DEFAULT GETDATE()
)

K.NARESH DBMS LAB MANUAL/WORKBOOK Page 23


The ALTER TABLE Statement
The ALTER TABLE statement is used to add, delete, or modify columns or change their sizes, change their
datatypes in an existing table.

Syntax
To add a column in a table, use the following syntax:
ALTER TABLE table_name ADD column_name datatype;

To delete a column in a table, use the following syntax (notice that some database systems don't allow
deleting a column):
ALTER TABLE table_name DROP COLUMN column_name;

To change the data type of a column in a table, use the following syntax:
ALTER TABLE table_name MODIFY column_name datatype;

The SQL ALTER TABLE command is used to modify the definition (structure) of a table by modifying the
definition of its columns. The ALTER command is used to perform the following functions.
1) Add, drop, modify table columns
2) Add and drop constraints
3) Enable and Disable constraints

Syntax to add a column


ALTER TABLE table_name ADD column_name datatype;

Eg: To add a column "experience" to the employee table, the query would be like
ALTER TABLE employee ADD experience number(3);

Syntax to drop a column


ALTER TABLE table_name DROP column_name;

Eg: To drop the column "location" from the employee table, the query would be like
ALTER TABLE employee DROP location;

Syntax to modify a column


ALTER TABLE table_name MODIFY column_name datatype;

Eg. To modify the column salary in the employee table, the query would be like
ALTER TABLE employee MODIFY salary number(15,2);

Add a column to the existing table emp, which will hold the grades for each employee
ALTER TABLE emp ADD grade CHAR(2);

Modify the emp table, add a Primary Key constraint ‘emp_c’


ALTER TABLE emp ADD CONSTRAINT emp_c PRIMARY KEY(empno);

Modify the emp table, add constraint REFERENCES to deptno of table emp referring deptno of table dept
ALTER TABLE emp ADD CONSTRAINT pk_c FOREIGN KEY (deptno) REFERENCES dept(deptno);

Modify the emp table, add constraint CHECK for sal of table emp where sal should be greater than 2500
ALTER TABLE emp ADD CONSTRAINT chk_sal CHECK (sal > 2500);

Modify the sal column of the emp table to NOT NULL and increases its size to 10
ALTER TABLE emp MODIFY sal NUMBER(10,2) NOT NULL;

K.NARESH DBMS LAB MANUAL/WORKBOOK Page 24


Modify the ename column. Increase its width to varchar2(35)
ALTER TABLE emp MODIFY ename varchar2(35);

To drop constraints:
ALTER TABLE <tablename> DROP <constraints>;

ALTER TABLE emp DROP CONSTRAINT emp_sal;


ALTER TABLE emp DROP PRIMARY KEY;

ALTER TABLE emp DISABLE CONSTRAINT emp_comm CASCADE;


The keyword CASCADE disables the dependent constraints also.

SQL RENAME Command


The SQL RENAME command is used to change the name of the table or a database object.
If you change the object's name any reference to the old name will be affected. You have to manually change
the old name to the new name in every reference.

Syntax
RENAME old_table_name To new_table_name;

Eg: To change the name of the table employee to my_employee, the query would be like
RENAME employee TO my_employee;

K.NARESH DBMS LAB MANUAL/WORKBOOK Page 25


Hands on Session

1. Create Table: Sailors


Field Name Not Null Datatype
Sid primary key integer
Sname varchar2(20)
Rating integer
Age decimal(4,1)

2. Create Table: Boats


Field Name Not Null Datatype
Bid Primary Key integer
Bname varchar2(20)
Color varchar2(20)

3. Create Table: Reserves


Field Name Not Null Datatype
Sid primary key, Foreign key(Sailors) integer
Bid primary key, Foreign key(Boats) integer
Day primary key date

4. Insert data in to sailors

Sid Sname Rating Age


22 DUSTIN 7 45.0
29 BRUTUS 1 33.0
31 LUBBER 8 55.5
32 ANDY 8 25.5
58 RUSTY 10 35.0
64 HORATIO 7 35.0
71 ZORBA 10 16.0
74 HORATIO 9 35.0
85 ART 3 25.5
95 BOB 3 63.5

5. Insert records in to Boats

Bid Bname Color


101 INTERLAKE BLUE
102 INTERLAKE RED
103 CLIPPER GREEN
104 MARINE RED

6. Insert records in to Reserves


Sid Bid Day
22 101 10-OCT-98
22 102 10-OCT-98
22 103 8-OCT-98
22 104 7-OCT-98
31 102 10-NOV-98
31 103 6-NOV-98
31 104 12-NOV-98
64 101 5-SEP-98
64 102 8-SEP-98
74 103 8-SEP-98

K.NARESH DBMS LAB MANUAL/WORKBOOK Page 26


insert into Sailors (sid,sname,rating,age)REM values(131,'Lubber',8,55.5);
insert into Reserves(sid,bid,day) values(131,101,'8-OCT-98');

1. "Find the names of sailors who have reserved boat number 103"
2. "Find the names of sailors who have never reserved boat number 103"
3. "Find the names of sailors who have reserved a red boat"
4. "Find the colors of boats reserved by Lubber"
5. "Find the names of sailors who have reserved at least one boat"
6. "Find the names of sailors who have reserved a red or a green boat"
7. "Find the names of sailors who have reserved both a red and a green boat"
8. "Find the names of sailors who have reserved a red but not a green boat"
9. "Find the names of sailors who have reserved at least two different boats"
10. "Find the names of sailors who have reserved at least n boats"
11. “Find the sids of sailors with age over 20 who have not reserved a red boat"
12. "Find the names of sailors who have reserved all boats"
13. "Find the names of sailors who have reserved all boats called Interlake"
14. “Find all sailors with a rating above 7"
15. "Find the names and ages of sailors with a rating above 7"
16. "Find the sailor name boat id and reservation date for each reservation"
17. "Find sailors who have reserved all red boats"
18. "Find the names and ages of all sailors"
19. "Find the sids of sailors who have reserved a red boat"
20. "Compute increments for the ratings of persons who have sailed two different boats on the same day"
21. “Find the ages of sailors whose name begins and ends with B and has at least three characters”
22. “Find the sids of all sailors who have reserved red boats but not green boats”
23. "Find all sids of sailors who have a rating of 10 or have reserved boat 104"
24. "Find the names of sailors who have not reserved a red boat"
25. "Find sailors whose rating is better than some sailor called Horatio"
26. "Find sailors whose rating is better than every sailor called Horatio"
27. "Find the sailors with the highest rating"
28. "Find the average of all sailors"
29. "Find the average age of sailors with a rating of 10"
30. "Find the name and age of the oldest sailor"
31. "Count the number of sailors"
32. "Count the number of different sailor names"
33. "Find the names of sailors who are older than the oldest sailor with a rating of 10"
34. "Find the age of the youngest sailor for each rating level"
35. "Find the age of the youngest sailor who is eligible to vote(i.e., is at least 18 years old) for each rating level
with at least two such sailors"
36. "For each red boat, find the number of reservations for this boat"
37. "Find the average age of sailors for each rating level that has at least two sailors"
38. "Find the average age of sailors who are of voting age(i.e., at least 18 years old) for each rating level that
has at least two sailors"
39. "Find the average age of sailors who are of voting age(i.e., at least 18 years old) for each rating level that
has at least two such sailors"
40. "Find those ratings for which the average age of sailors in the minimum overall ratings"
41. "Find the sailor ids with top 5 rating ranks."

K.NARESH DBMS LAB MANUAL/WORKBOOK Page 27


NULL values represent missing unknown data.
By default, a table column can hold NULL values.
If a column in a table is optional, we can insert a new record or update an existing record without adding a
value to this column. This means that the field will be saved with a NULL value.
NULL values are treated differently from other values.
NULL is used as a placeholder for unknown or inapplicable values.
Note: It is not possible to compare NULL and 0; they are not equivalent.

SQL NVL() Function


The Oracle NVL() function allows you to replace null with a more meaningful alternative in the results of a
query.
The following shows the syntax of the NVL() function: NVL(e1, e2)
The NVL() function accepts two arguments. If e1 evaluates to null, then NVL() function returns e2.
If e1 evaluates to non-null, the NVL() function returns e1.
The two arguments e1 and e2 can have the same or different data types. If their data types are different,
Oracle implicit converts one to the other according to the following rules:
 If the data type of e1 is character, Oracle converts e2 to the data type of e1 before comparing them
with null and returns VARCHAR2 in the character set of e1.
 If the data type of e1 is numeric, Oracle determines which argument has the highest numeric
precedence, implicitly converts the other argument to that data type, and returns that data type.
 If Oracle cannot implicitly convert one data type to the other, then it issues an error.

1. SELECT NVL(100,200) FROM dual;


Returns 100 because the first argument is not null.

2. SELECT NVL(NULL, 'N/A') FROM dual;


returns N/A because the first argument is null:

3. List the name, salary, and comm. For those employees whose net pay is greater than or equal to any other
employee salary of the company.
A) select e.ename, e.sal, e.comm
from emp e
where nvl2(e.comm.,e.sal+e.comm,e.sal) >= any (select sal from emp);
(OR)
B) select ename,sal,comm. from emp
where sal+nvl(comm,0) >= any (select sal from emp);/

4. List the Name , Salary, Comm and Net Pay is more than any other employee.
Select e.ename, e.sal, e.comm, nvl2(comm, sal+comm, sal) NETPAY
from emp e
where nvl2(comm, sal+comm, sal) > any (select sal from emp where empno = e.empno) ;

5. List the Deptno, Name, Job, Salary and Sal+Comm of the SALESMAN who are earning maximum salary
and commission in descending order.
Select deptno, name, job, sal, sal+nvl(comm,0) from emp
where job = ‘SALESMAN’
and sal in
(select max(sal+nvl(comm, 0)) from emp where comm is not null)
Order by (sal +nvl(comm.,0)) desc;

6. List the Deptno, Name, Job, Salary and Sal+Comm of the emps who earn the second highest earnings (sal
+ comm.).
Select deptno, ename, sal, job, sal+nvl(comm,0)

K.NARESH DBMS LAB MANUAL/WORKBOOK Page 28


from emp e
where 2 = (select count(distinct sal + nvl(comm, 0)) from emp where (e.sal+nvl(comm.,0))<(sal+nvl(comm,0));

7. List the Emps whose Sal is > the total remuneration of the SALESMAN.
select * from emp
where sal > (select sum(nvl2(comm, sal+comm, sal)) from emp where job = ‘SALESMAN’);

The NVL(), IFNULL(), and COALESCE() functions can also be used to achieve the same result.

Oracle NVL() vs. COALESCE()


The COALESCE() function is a generalization of the NVL() function.
The following function: NVL(e1,e2)
returns the same result as
COALESCE (e1, e2)
However, the COALESCE() function evaluates its argument in order and stops evaluation when it can
determine the result i.e., when it can find the first non-NULL argument. This feature is known as short-circuit
evaluation. In contrast, the NVL() function evaluates all of its arguments to determine the result.

K.NARESH DBMS LAB MANUAL/WORKBOOK Page 29


A view is a virtual table.
This chapter shows how to create, update, and delete a view.

A VIEW is a virtual table, through which a selective portion of the data from one or more tables can be seen.
Views do not contain data of their own. They are used to restrict access to the database or to hide data
complexity. A view is stored as a SELECT statement in the database. DML operations on a view like INSER T,
UPDATE, DELETE affects the data in the original table upon which the view is based.

In SQL, a view is a virtual table based on the result-set of an SQL statement.


A view contains rows and columns, just like a real table. The fields in a view are fields from one or more real
tables in the database.
You can add SQL functions, WHERE, and JOIN statements to a view and present the data as if the data were
coming from one single table.

The changes in the tables are automatically reflected in the VIEWs.

Syntax
CREATE VIEW view_name AS
SELECT column_name(s) FROM table_name WHERE condition;

Note: A view always shows up-to-date data! The database engine recreates the data, using the view's SQL
statement, every time a user queries a view.

SQL CREATE OR REPLACE VIEW Syntax

CREATE OR REPLACE VIEW view_name AS


SELECT column_name(s) FROM table_name WHERE condition

SQL DROP VIEW Syntax


DROP VIEW view_name

Create a VIEW for the employees belonging to dept number 20.


CREATE VIEW dept20 AS SELECT * FROM emp WHERE deptno = 20;

To display view details:


SELECT * from dept20;

Create a VIEW for the employees belonging to dept number 20.


CREATE VIEW dept20 AS SELECT empno, ename, deptno FROM dept WHERE deptno = 20;

Functions
Functions are used to manipulate data items.

Advantages:
Can be used to perform complex calculations on data
Can modify individual data items
Can very easily manipulate output for group of rows
Can alter date formats for display

Types of functions: 1. Single-row function 2. Group Function


Column Functions: Arithmetic functions, Character functions, date functions, general functions

Arithmetic Functions
1. ABS(n) – This function returns absolute value of the column or value passed
Sql> SELECT ABS(-65) FROM dual;

K.NARESH DBMS LAB MANUAL/WORKBOOK Page 30


2. CEIL(n) – This function finds the smallest integer greater than or equal to n. n can be a column name also.
SELECT CEIL(sal) FROM emp WHERE sal BETWEEN 3000 AND 5000;

3. FLOOR(n) – This function finds the largest integer less than or equal to the value of n. n can be either
column or expression.
SELECT FLOOR(sal), CEIL(88.9) FROM emp WHERE sal BETWEEN 3000 AND 5000;

4. MOD(m, n) – This function returns the remainder of m divided by n; or m if n=0;


SELECT MOD(200,30) FROM dual;

5. POWER(m, n) – This function returns m raised to the power of n. The second argument n must be an
integer.
SELECT sal, POWER(sal, 2) FROM emp WHERE deptno = 10;

6. SIGN(n) – This function returns -1 if n is negative, it returns 1 if n is positive and it returns 0 if n is 0.


SELECT comm-sal, SIGN(comm-sal) FROM emp WHERE deptno = 30;

7. SQRT(n) – This function returns the square root of n. If value n is NULL or negative, then NULL is returned.
SELECT sal, SQRT(sal) FROM emp WHERE deptno=10;

8. TRUNC(m, [n]) – This function truncates the m or column to n decimal places, If n is omitted then it is
truncated to no decimal places. If n is negative then numbers left of decimal places are truncated to 0.
SELECT TRUNC(90.723, 1), TRUNC(90.723, -1), TRUNC(90.723) FROM dual;

Try these functions:

SQL>SELECT ACOS(1) FROM dual;


SQL>SELECT ASIN(1) FROM dual;
SQL>SELECT ATAN(1) FROM dual;
SQL>SELECT ATAN2(3,6) FROM dual;
SQL>SELECT LEAST(6,1,2,3,4,5,6,7,8,9,10) FROM dual;
SQL>SELECT LOG(2,65536) FROM DUAL;
SQL>SELECT ROUND(5.693893) FROM DUAL;
SQL>SELECT ROUND(5.693893,2) FROM DUAL;
SQL>SELECT SIN(90) FROM DUAL;
SQL>SELECT COS(0) FROM DUAL;
SELECT TAN(45) FROM DUAL;

SQL string functions are used primarily for string manipulation.

ASCII(str) - Returns the numeric value of the leftmost character of the string str. Returns 0 if str is the empty
string. Returns NULL if str is NULL. ASCII() works for characters with numeric values from 0 to 255.
SQL>SELECT ASCII('2') FROM DUAL;

INSTR(str,substr) Returns the position of the first occurrence of substring substr in string str.
SQL>SELECT INSTR('foobarbar', 'bar') FROM DUAL;

LOWER(str) Function return lowercase character in every word.


SQL>SELECT LOWER(‘RUPA’) FROM DUAL;

LENGTH(str) Returns the length of the string str, measured in bytes. A multi-byte character counts as
multiple bytes. This means that for a string containing five two-byte characters, LENGTH() returns 10,
whereas CHAR_LENGTH() returns 5.

K.NARESH DBMS LAB MANUAL/WORKBOOK Page 31


SQL> SELECT LENGTH('text') FROM DUAL;

LPAD(str,len,padstr) Returns the string str, left-padded with the string padstr to a length of len characters. If
str is longer than len, the return value is shortened to len characters.
SQL> SELECT LPAD('hi',4,'??') FROM DUAL;

LTRIM(str) Returns the string str with leading space characters removed.
SQL> SELECT LTRIM(' barbar') FROM DUAL;

REPLACE(str,from_str,to_str) Returns the string str with all occurrences of the string from_str replaced by
the string to_str. REPLACE() performs a case-sensitive match when searching for from_str.
SQL> SELECT REPLACE('www.whatawalk.com', 'w', 'Ww') FROM DUAL;

REVERSE(str) Returns the string str with the order of the characters reversed.
SQL> SELECT REVERSE('abcd') FROM DUAL;

RPAD(str,len,padstr) Returns the string str, right-padded with the string padstr to a length of len
characters. If str is longer than len, the return value is shortened to len characters.
SQL> SELECT RPAD('hi',5,'?') FROM DUAL;

RTRIM(str) Returns the string str with trailing space characters removed.
SQL> SELECT RTRIM('barbar ') FROM DUAL;

TRIM(str) Returns the string str with all rem str prefixes or suffixes removed. If none of the specifiers BOTH,
LEADING, or TRAILING is given, BOTH is assumed. remstr is optional and, if not specified, spaces are
removed.
SQL> SELECT TRIM(' bar ‘) FROM DUAL;

UPPER(str) Returns the string str with all characters changed to uppercase according to the current
character set mapping.
SQL> SELECT UPPER(‘Rupa Devi Singh') FROM DUAL;

DATE Functions
SYSDATE is a pseudo-column that returns the current date and time of type DATE.
SQL>SELECT SYSDATE FROM dual;

ADD_MONTHS(d, n)- Adds or subtracts months to or from a date. Returns a date as a result
SQL>SELECT hiredate, ADD_MONTHS(hiredate, 4), ADD_MONTHS(hiredate, -4) FROM emprd WHERE
deptno=10;

ROUND(d [,format]) - This function rounds the date d to the unit specified by format. If format is not specified,
it defaults to ‘DD’, which rounds to the nearest day
SQL>SELECT ROUND(TO_DATE(’12-APR-91’),’MM’) “Nearest Month” FROM dual;

TRUNC(d [,format]) - This function returns the date d truncated to the unit specified by format. If format is
omitted, it defaults to ‘DD’, which truncates d to the nearest day
SQL>SELECT TRUNC(TO_DATE(’12-APR-91 13:21:00’,’DD-MON-YY HH24:MI:SS’, ‘Year’) “First Day” FROM
dual;

MONTHS_BETWEEN(d1,d2) - This function returns the number of months between two dates, d1 and d2. If
d1 is later than d2, the result is positive else negative. The output will be a number.
SQL>SELECT MONTHS_BETWEEN(’05-JUN-98’, ’05-DEC-99’), MONTHS_BETWEEN(’05-DEC-99’, ’05-JUN-
98’), MONTHS_BETWEEN(’05-JUN-98’,’05-JUN-98’) FROM dual;

K.NARESH DBMS LAB MANUAL/WORKBOOK Page 32


LAST_DAY(d) - This function returns the date of the last day of the month specified. The result will be a date.
SQL>SELECT SYSDATE, LAST_DAY(SYSDATE) FROM dual;

NEXT_DAY(date, day) -This function returns the date of next specified day of the week after the ‘date’.
SQL>SELECT SYSDATE, NEXT_DAY(SYSDATE, Wednesday) FROM dual;

TO_CHAR(d, f) - This function converts the date ‘d’ to character format f.


SQL>SELECT SYSDATE, TO_CHAR(SYSDATE, ’DAY’) FROM dual;

TO_DATE(char, f) - This function converts the character string representing date into a date format according
to ‘f’ format specified. If no format is specified the default format is ‘DD-MON-YY’.

Format Description example


MM Number of month 10
RM Roman numeral of month X
MON Three letter abbreviation of month OCT
MONTH Full Month Spelled OCTOBER
DDD Number of days since Jan 1 321
DD Number of day in the month 14
D Number of the day in week 5
DY Three letter abbreviation of day Fri
DAY Full Day Spelled Friday
YYYY Full 4 digit year 2016
SYYYY Signed Year
YYY Last three digits of year 016
YY Last two digits of year 16
Y Last digit of year 6
YEAR Year spelt out TWO THOUSAND SIXTEEN

SQL>SELECT TO_CHAR(TO_DATE(SYSDATE),’RM’) FROM dual;

K.NARESH DBMS LAB MANUAL/WORKBOOK Page 33


PL/SQL stands for Procedural Language extension of SQL.

PL/SQL is a combination of SQL along with the procedural features of programming languages.

It was developed by Oracle Corporation in the early 90’s to enhance the capabilities of SQL.

The PL/SQL Engine:

Oracle uses a PL/SQL engine to processes the PL/SQL statements. A PL/SQL language code can be stored in
the client system (client-side) or in the database (server-side).

A Simple PL/SQL Block:

Each PL/SQL program consists of SQL and PL/SQL statements which from a PL/SQL block.

PL/SQL Block consists of three sections:

 The Declaration section (optional).


 The Execution section (mandatory).
 The Exception Handling (or Error) section (optional).

SQL Command Categories

SQL commands are grouped into four major categories depending on their functionality. They are as follows:

Data Definition Language (DDL)

These SQL commands are used for creating, modifying, and dropping the structure of database objects. The
commands are CREATE, ALTER, DROP, RENAME, and TRUNCATE.

Data Manipulation Language (DML)

These SQL commands are used for storing, retrieving, modifying, and deleting data. These commands are
SELECT, INSERT, UPDATE, and DELETE.

Transaction Control Language (TCL)

These SQL commands are used for managing changes affecting the data. These commands are COMMIT,
ROLLBACK, and SAVEPOINT.

Data Control Language (DCL)

These SQL commands are used for providing security to database objects. These commands are GRANT and
REVOKE.

Advantages of PL/SQL

K.NARESH DBMS LAB MANUAL/WORKBOOK Page 34


 Block Structures: PL SQL consists of blocks of code, which can be nested within each other. Each
block forms a unit of a task or a logical module. PL/SQL Blocks can be stored in the database and
reused.
 Procedural Language Capability: PL SQL consists of procedural language constructs such as
conditional statements (if else statements) and loops like (FOR loops).
 Better Performance: PL SQL engine processes multiple SQL statements simultaneously as a single
block, thereby reducing network traffic.
 Error Handling: PL/SQL handles errors or exceptions effectively during the execution of a PL/SQL
program. Once an exception is caught, specific actions can be taken depending upon the type of the
exception or it can be displayed to the user with a message.

Program 1: To Print Hello World on the screen


SET SERVEROUTPUT ON
SQL> begin
2 dbms_output.put_line('Hello World');
3 end;
4 /
Hello World

PL/SQL procedure successfully completed.

Program 2: To show the variable assignments and expressions


DECLARE
str1 VARCHAR2(10);
str2 VARCHAR2(15);
num1 number;
BEGIN
str1 := 'Good Bye';
str2 := str1;
num1 := 34.9;
DBMS_OUTPUT.PUT_LINE(str1 || str2 || num1);
END;
/
Good ByeGood Bye34.9

PL/SQL procedure successfully completed.

Program 3: To show multiplication of two numbers


DECLARE
var_num1 number;
var_num2 number;
BEGIN
var_num1 := 100;
var_num2 := 200;
DECLARE
var_mult number;
BEGIN
var_mult := var_num1 * var_num2;
DBMS_OUTPUT.PUT_LINE(var_mult);
END;
END;
/
20000

PL/SQL procedure successfully completed.

Program 4: Prog to show the usage of comment lines


DECLARE

K.NARESH DBMS LAB MANUAL/WORKBOOK Page 35


-- variable declaration
message varchar2(20):= 'Hello, World!';
BEGIN
/*
* PL/SQL executable statement(s)
*/
dbms_output.put_line(message);
END;
/
Hello, World!

PL/SQL procedure successfully completed.

Program 5: To make use of various types of variables:


DECLARE
a integer := 10;
b integer := 20;
c integer;
f real;
BEGIN
c := a + b;
dbms_output.put_line('Value of c: ' || c);
f := 70.0/3.0;
dbms_output.put_line('Value of f: ' || f);
END;
/
Value of c: 30
Value of f: 23.33333333333333333333333333333333333333

PL/SQL procedure successfully completed.

Program 6: To show the usage of Local and Global variables in its simple form

DECLARE
-- Global variables
num1 number := 95;
num2 number := 85;
BEGIN
dbms_output.put_line('Outer Variable num1: ' || num1);
dbms_output.put_line('Outer Variable num2: ' || num2);
DECLARE
-- Local variables
num1 number := 195;
num2 number := 185;
BEGIN
dbms_output.put_line('Inner Variable num1: ' || num1);
dbms_output.put_line('Inner Variable num2: ' || num2);
END;
END;
/

Outer Variable num1: 95


Outer Variable num2: 85
Inner Variable num1: 195
Inner Variable num2: 185

PL/SQL procedure successfully completed.

Program 7: To show the usage of a constant

K.NARESH DBMS LAB MANUAL/WORKBOOK Page 36


DECLARE
-- constant declaration
pi constant number := 3.141592654;
-- other declarations
radius number(5,2);
dia number(5,2);
circumference number(7, 2);
area number (10, 2);
BEGIN
-- processing
radius := 9.5;
dia := radius * 2;
circumference := 2.0 * pi * radius;
area := pi * radius * radius;
-- output
dbms_output.put_line('Radius: ' || radius);
dbms_output.put_line('Diameter: ' || dia);
dbms_output.put_line('Circumference: ' || circumference);
dbms_output.put_line('Area: ' || area);
END;
/
Radius: 9.5
Diameter: 19
Circumference: 59.69
Area: 283.53

PL/SQL procedure successfully completed.

Program 8: To show the usage of arithmetic operators


BEGIN
dbms_output.put_line( 10 + 5);
dbms_output.put_line( 10 - 5);
dbms_output.put_line( 10 * 5);
dbms_output.put_line( 10 / 5);
dbms_output.put_line( 10 ** 5);
END;
/
15
5
50
2
100000

PL/SQL procedure successfully completed.

Program 9: To show the working of Relational Operators


DECLARE
a number (2) := 21;
b number (2) := 10;
BEGIN
IF (a = b) then
dbms_output.put_line('Line 1 - a is equal to b');
ELSE
dbms_output.put_line('Line 1 - a is not equal to b');
END IF;

IF (a < b) then
dbms_output.put_line('Line 2 - a is less than b');
ELSE
dbms_output.put_line('Line 2 - a is not less than b');
END IF;

K.NARESH DBMS LAB MANUAL/WORKBOOK Page 37


IF ( a > b ) THEN
dbms_output.put_line('Line 3 - a is greater than b');
ELSE
dbms_output.put_line('Line 3 - a is not greater than b');
END IF;

-- Lets change value of a and b


a := 5;
b := 20;
IF ( a <= b ) THEN
dbms_output.put_line('Line 4 - a is either equal or less than b');
END IF;

IF ( b >= a ) THEN
dbms_output.put_line('Line 5 - b is either equal or greater than a');
END IF;

IF ( a <> b ) THEN
dbms_output.put_line('Line 6 - a is not equal to b');
ELSE
dbms_output.put_line('Line 6 - a is equal to b');
END IF;

END;
/
Line 1 - a is not equal to b
Line 2 - a is not less than b
Line 3 - a is greater than b
Line 4 - a is either equal or less than b
Line 5 - b is either equal or greater than a
Line 6 - a is not equal to b

PL/SQL procedure successfully completed

Program 10: To show the working of LIKE Operator


DECLARE
PROCEDURE compare (value varchar2, pattern varchar2 ) is
BEGIN
IF value LIKE pattern THEN
dbms_output.put_line ('True');
ELSE
dbms_output.put_line ('False');
END IF;
END;

BEGIN
compare('Zara Ali', 'Z%A_i');
compare('Nuha Ali', 'Z% A_i');
END;
/
True
False

PL/SQL procedure successfully completed.

Program 11: To show the usage of the BETWEEN operator


DECLARE
x number(2) := 10;
BEGIN
IF (x between 5 and 20) THEN

K.NARESH DBMS LAB MANUAL/WORKBOOK Page 38


dbms_output.put_line('True');
ELSE
dbms_output.put_line('False');
END IF;

IF (x BETWEEN 5 AND 10) THEN


dbms_output.put_line('True');
ELSE
dbms_output.put_line('False');
END IF;

IF (x BETWEEN 11 AND 20) THEN


dbms_output.put_line('True');
ELSE
dbms_output.put_line('False');
END IF;
END;
/
True
True
False

PL/SQL procedure successfully completed.

Program 12: Program to show the usage of IN operator


DECLARE
letter varchar2(1) := 'm';
BEGIN
IF (letter in ('a', 'b', 'c')) THEN
dbms_output.put_line('True');
ELSE
dbms_output.put_line('False');
END IF;

IF (letter in ('m', 'n', 'o')) THEN


dbms_output.put_line('True');
ELSE
dbms_output.put_line('False');
END IF;

IF (letter is null) THEN


dbms_output.put_line('True');
ELSE
dbms_output.put_line('False');
END IF;
END;
/
False
True
False

PL/SQL procedure successfully completed.

Program 13: Program to show the usage of Logical operator


DECLARE
a boolean := true;
b boolean := false;
BEGIN
IF (a AND b) THEN
dbms_output.put_line('Line 1 - Condition is true');

K.NARESH DBMS LAB MANUAL/WORKBOOK Page 39


END IF;
IF (a OR b) THEN
dbms_output.put_line('Line 2 - Condition is true');
END IF;
IF (NOT a) THEN
dbms_output.put_line('Line 3 - a is not true');
ELSE
dbms_output.put_line('Line 3 - a is true');
END IF;
IF (NOT b) THEN
dbms_output.put_line('Line 4 - b is not true');
ELSE
dbms_output.put_line('Line 4 - b is true');
END IF;
END;
/
Line 2 - Condition is true
Line 3 - a is true
Line 4 - b is not true

PL/SQL procedure successfully completed.

Program 14: To understand Operator Precedence


DECLARE
a number(2) := 20;
b number(2) := 10;
c number(2) := 15;
d number(2) := 5;
e number(2) ;
BEGIN
e := (a + b) * c / d; -- ( 30 * 15 ) / 5
dbms_output.put_line('Value of (a + b) * c / d is : '|| e );

e := ((a + b) * c) / d; -- (30 * 15 ) / 5
dbms_output.put_line('Value of ((a + b) * c) / d is : ' || e );

e := (a + b) * (c / d); -- (30) * (15/5)


dbms_output.put_line('Value of (a + b) * (c / d) is : '|| e );

e := a + (b * c) / d; -- 20 + (150/5)
dbms_output.put_line('Value of a + (b * c) / d is : ' || e );
END;
/
Value of (a + b) * c / d is : 90
Value of ((a + b) * c) / d is : 90
Value of (a + b) * (c / d) is : 90
Value of a + (b * c) / d is : 50

PL/SQL procedure successfully completed.

Program 15: To illustrate the concept of if statement


DECLARE
a number(2) := 10;
BEGIN
a:= 10;
-- check the boolean condition using if statement
IF( a < 20 ) THEN
-- if condition is true then print the following
dbms_output.put_line('a is less than 20 ' );
END IF;
dbms_output.put_line('value of a is : ' || a);

K.NARESH DBMS LAB MANUAL/WORKBOOK Page 40


END;
/

a is less than 20
value of a is : 10

PL/SQL procedure successfully completed.

Program 16: To illustrate the concept of if-then-else statement


DECLARE
a number(3) := 100;
BEGIN
-- check the boolean condition using if statement
IF( a < 20 ) THEN
-- if condition is true then print the following
dbms_output.put_line('a is less than 20 ' );
ELSE
dbms_output.put_line('a is not less than 20 ' );
END IF;
dbms_output.put_line('value of a is : ' || a);
END;
/
a is not less than 20
value of a is : 100

PL/SQL procedure successfully completed.

Program 17: To illustrate the concept of if-then-elsif statement


DECLARE
a number(3) := 100;
BEGIN
IF ( a = 10 ) THEN
dbms_output.put_line('Value of a is 10' );
ELSIF ( a = 20 ) THEN
dbms_output.put_line('Value of a is 20' );
ELSIF ( a = 30 ) THEN
dbms_output.put_line('Value of a is 30' );
ELSE
dbms_output.put_line('None of the values is matching');
END IF;
dbms_output.put_line('Exact value of a is: '|| a );
END;
/
None of the values is matching
Exact value of a is: 100

PL/SQL procedure successfully completed.

Program 18: To illustrate the concept of case statement


DECLARE
grade char(1) := 'A';
BEGIN
CASE grade
when 'A' then dbms_output.put_line('Excellent');
when 'B' then dbms_output.put_line('Very good');
when 'C' then dbms_output.put_line('Well done');
when 'D' then dbms_output.put_line('You passed');
when 'F' then dbms_output.put_line('Better try again');
else dbms_output.put_line('No such grade');
END CASE;
END;

K.NARESH DBMS LAB MANUAL/WORKBOOK Page 41


/
Excellent

PL/SQL procedure successfully completed.

Prog 19:
DECLARE
grade char(1) := 'B';
BEGIN
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('Well done');
when grade = 'D' then dbms_output.put_line('You passed');
when grade = 'F' then dbms_output.put_line('Better try again');
else dbms_output.put_line('No such grade');
end case;
END;
/
Very good

PL/SQL procedure successfully completed.

Program 20: To illustrate the concept of nested-if statement


DECLARE
a number(3) := 100;
b number(3) := 200;
BEGIN
-- check the boolean condition
IF( a = 100 ) THEN
-- if condition is true then check the following
IF( b = 200 ) THEN
-- if condition is true then print the following
dbms_output.put_line('Value of a is 100 and b is 200' );
END IF;
END IF;
dbms_output.put_line('Exact value of a is : ' || a );
dbms_output.put_line('Exact value of b is : ' || b );
END;
/
Value of a is 100 and b is 200
Exact value of a is : 100
Exact value of b is : 200

PL/SQL procedure successfully completed.

Program 21: To illustrate the concept of labeling loop


DECLARE
i number(1);
j number(1);
BEGIN
<< outer_loop >>
FOR i IN 1..3 LOOP
<< inner_loop >>
FOR j IN 1..3 LOOP
dbms_output.put_line('i is: '|| i || ' and j is: ' || j);
END loop inner_loop;
END loop outer_loop;
END;
/
i is: 1 and j is: 1

K.NARESH DBMS LAB MANUAL/WORKBOOK Page 42


i is: 1 and j is: 2
i is: 1 and j is: 3
i is: 2 and j is: 1
i is: 2 and j is: 2
i is: 2 and j is: 3
i is: 3 and j is: 1
i is: 3 and j is: 2
i is: 3 and j is: 3

PL/SQL procedure successfully completed.

Program 22: To illustrate basic loop


DECLARE
x number := 10;
BEGIN
LOOP
dbms_output.put_line(x);
x := x + 10;
IF x > 50 THEN
exit;
END IF;
END LOOP;
-- after exit, control resumes here
dbms_output.put_line('After Exit x is: ' || x);
END;
/
10
20
30
40
50
After Exit x is: 60

PL/SQL procedure successfully completed.

Prog 23: Using EXIT WHEN Statement


DECLARE
x number := 10;
BEGIN
LOOP
dbms_output.put_line(x);
x := x + 10;
exit WHEN x > 50;
END LOOP;
-- after exit, control resumes here
dbms_output.put_line('After Exit x is: ' || x);
END;
/
10
20
30
40
50
After Exit x is: 60

PL/SQL procedure successfully completed.

Program 24: To illustrate WHILE loop statement


DECLARE
a number(2) := 10;
BEGIN

K.NARESH DBMS LAB MANUAL/WORKBOOK Page 43


WHILE a < 20 LOOP
dbms_output.put_line('value of a: ' || a);
a := a + 1;
END LOOP;
END;
/
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19

PL/SQL procedure successfully completed.

Program 25: To illustrate the usage of for loop


DECLARE
a number(2);
BEGIN
FOR a in 10 .. 20 LOOP
dbms_output.put_line('value of a: ' || a);
END LOOP;
END;
/
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
value of a: 20

PL/SQL procedure successfully completed.

Program 26: To illustrate the reverse for loop


DECLARE
a number(2) ;
BEGIN
FOR a IN REVERSE 10 .. 20 LOOP
dbms_output.put_line('value of a: ' || a);
END LOOP;
END;
/
value of a: 20
value of a: 19
value of a: 18
value of a: 17
value of a: 16
value of a: 15
value of a: 14
value of a: 13
value of a: 12
value of a: 11

K.NARESH DBMS LAB MANUAL/WORKBOOK Page 44


value of a: 10

PL/SQL procedure successfully completed.

Program 27: To print Prime numbers from 2 to 50


DECLARE
i number(3);
j number(3);
BEGIN
i := 2;
LOOP
j:= 2;
LOOP
exit WHEN ((mod(i, j) = 0) or (j = i));
j := j +1;
END LOOP;
IF (j = i ) THEN
dbms_output.put_line(i || ' is prime');
END IF;
i := i + 1;
exit WHEN i = 50;
END LOOP;
END;
/
2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
23 is prime
29 is prime
31 is prime
37 is prime
41 is prime
43 is prime
47 is prime

PL/SQL procedure successfully completed.

Program 28: To illustrate the usage of CONTINUE statement


DECLARE
a number(2) := 10;
BEGIN
-- while loop execution
WHILE a < 20 LOOP
dbms_output.put_line ('value of a: ' || a);
a := a + 1;
IF a = 15 THEN
-- skip the loop using the CONTINUE statement
a := a + 1;
CONTINUE;
END IF;
END LOOP;
END;
/

K.NARESH DBMS LAB MANUAL/WORKBOOK Page 45


value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19

PL/SQL procedure successfully completed.

Program 29: To illustrate declaring and using string variables


DECLARE
name varchar2(20);
company varchar2(30);
introduction clob;
choice char(1);
BEGIN
name := 'John Smith';
company := 'Infotech';
introduction := ' Hello! I''m John Smith from Infotech.';
choice := 'y';
IF choice = 'y' THEN
dbms_output.put_line(name);
dbms_output.put_line(company);
dbms_output.put_line(introduction);
END IF;
END;
/
John Smith
Infotech Corporation
Hello! I'm John Smith from Infotech.

PL/SQL procedure successfully completed

Program 30: Write a PL/SQL code to update salary of employee number 7788 to 5000 if salary is less than OR
EQUAL TO 3000

DECLARE
x NUMBER(7,2);
BEGIN
SELECT sal INTO x FROM emp WHERE empno = 7788;
IF x <= 3000 THEN
UPDATE emp SET sal = 5000 WHERE empno = 7788;
END IF;
END;
/

Program 31: Update the commission of the empno 7369 to Rs. 300; if it is null; else raise his commission by
25%

DECLARE
var_empno NUMBER(4) := 7369;
var_comm emp.comm% TYPE;

BEGIN
SELECT comm INTO var_comm FROM emp
WHERE empno = var_empno;

IF var_comm IS NULL THEN

K.NARESH DBMS LAB MANUAL/WORKBOOK Page 46


UPDATE emp SET comm = 300
WHERE empno = var_empno;
ELSE
var_comm := var_comm + var_comm * 0.25;
UPDATE emp SET comm = var_comm
WHERE empno = var_empno;
END IF;
END;
/

A cursor is a temporary work area created in the system memory when a SQL statement is executed. A cursor
contains information on a select statement and the rows of data accessed by it.

This temporary work area is used to store the data retrieved from the database, and manipulate this data. A
cursor can hold more than one row, but can process only one row at a time. The set of rows the cursor holds
is called the active set.

There are two types of cursors in PL/SQL:

Implicit Cursors: Application

When you execute DML statements like DELETE, INSERT, UPDATE and SELECT statements, implicit
statements are created to process these statements.

Oracle provides few attributes called as implicit cursor attributes to check the status of DML operations. The
cursor attributes available are %FOUND, % NOTFOUND, % ROWCOUNT, and %ISOPEN.

For example, When you execute INSERT, UPDATE, or DELETE statements the cursor attributes tell us
whether any rows are affected and how many have been affected.
When a SELECT... INTO statement is executed in a PL/SQL Block, implicit cursor attributes can be used to
find out whether any row has been returned by the SELECT statement. PL/SQL returns an error when no
data is selected.

K.NARESH DBMS LAB MANUAL/WORKBOOK Page 47


The status of the cursor for each of these attributes are defined in the below table.
Attributes Return Value Example
%FOUND The return value is TRUE, if the DML statements like INSERT, SQL%FOUND
DELETE and UPDATE affect at least one row and if SELECT ….INTO
statement return at least one row.
The return value is FALSE, if DML statements like INSERT, DELETE
and UPDATE do not affect row and if SELECT….INTO statement do
not return a row.
%NOTFOUND The return value is FALSE, if DML statements like INSERT, DELETE SQL%NOTFOUND
and UPDATE at least one row and if SELECT ….INTO statement
return at least one row.
The return value is TRUE, if a DML statement like INSERT, DELETE
and UPDATE do not affect even one row and if SELECT ….INTO
statement does not return a row.
%ROWCOUNT Return the number of rows affected by the DML operations INSERT, SQL%ROWCOUNT
DELETE, UPDATE, SELECT

Program 32: Consider the PL/SQL Block that uses implicit cursor attributes as shown below:

DECLARE var_rows number(5);


BEGIN
UPDATE emp SET sal = sal + 1000;
IF SQL%NOTFOUND THEN
dbms_output.put_line('None of the salaries where updated');
ELSIF SQL%FOUND THEN
var_rows := SQL% ROWCOUNT;
dbms_output.put_line('Salaries for ' || var_rows || ' employees are updated');
END IF;
END;
/
Salaries for 14 employees are updated

PL/SQL procedure successfully completed.

Explicit Cursors

An explicit cursor is defined in the declaration section of the PL/SQL Block. It is created on a SELECT
Statement which returns more than one row. We can provide a suitable name for the cursor.
General Syntax for creating a cursor is as given below:
CURSOR cursor_name IS select_statement;

 cursor_name – A suitable name for the cursor.


 select_statement – A select query which returns multiple rows.

How to use Explicit Cursor?

There are four steps in using an Explicit Cursor.

 DECLARE the cursor in the declaration section.


 OPEN the cursor in the Execution Section.
 FETCH the data from cursor into PL/SQL variables or records in the Execution Section.
 CLOSE the cursor in the Execution Section before you end the PL/SQL Block.

1) Declaring a Cursor in the Declaration Section:


DECLARE
CURSOR emp_cur IS

K.NARESH DBMS LAB MANUAL/WORKBOOK Page 48


SELECT *
FROM emp
WHERE sal > 5000;

In the above example we are creating a cursor ‘emp_cur’ on a query which returns the records of all the
employees with salary greater than 5000. Here ‘emp_tbl’ in the table which contains records of all the
employees.

2) Accessing the records in the cursor:


Once the cursor is created in the declaration section we can access the cursor in the execution
section of the PL/SQL program.

How to access an Explicit Cursor?


These are the three steps in accessing the cursor.
1) Open the cursor.
2) Fetch the records in the cursor one at a time.
3) Close the cursor.

General Syntax to open a cursor is:


OPEN cursor_name;

General Syntax to fetch records from a cursor is:


FETCH cursor_name INTO record_name;
OR
FETCH cursor_name INTO variable_list;

General Syntax to close a cursor is:


CLOSE cursor_name;

When a cursor is opened, the first row becomes the current row. When the data is fetched it is copied to the
record or variables and the logical pointer moves to the next row and it becomes the current row. On every
fetch statement, the pointer moves to the next row. If you want to fetch after the last row, the program will
throw an error. When there is more than one row in a cursor we can use loops along with explicit cursor
attributes to fetch all the records.

Points to remember while fetching a row:

· We can fetch the rows in a cursor to a PL/SQL Record or a list of variables created in the PL/SQL Block.
· If you are fetching a cursor to a PL/SQL Record, the record should have the same structure as the cursor.
· If you are fetching a cursor to a list of variables, the variables should be listed in the same order in the fetch
statement as the columns are present in the cursor.

General Form of using an explicit cursor is:


DECLARE
variables;
records;
create a cursor;
BEGIN
OPEN cursor;
FETCH cursor;
process the records;
CLOSE cursor;
END;

Program 33: To illustrate the working of explicit cursor

Following is a complete example to illustrate the concepts of explicit cursors:


DECLARE

K.NARESH DBMS LAB MANUAL/WORKBOOK Page 49


c_empno emprd.empno%type;
c_ename emprd.ename% type;
c_sal emprd.sal%type;
CURSOR c_emp is
SELECT empno, ename, sal FROM emprd;
BEGIN
OPEN c_emp;
LOOP
FETCH c_emp into c_empno, c_ename, c_sal;
EXIT WHEN c_emp%notfound;
dbms_output.put_line(c_empno || ' ' || c_ename || ' ' || c_sal);
END LOOP;
CLOSE c_emp;
END;
/
7369 SMITH 1800
7499 ALLEN 2600
7521 WARD 2250
7566 JONES 3975
7654 MARTIN 2250
7698 BLAKE 3850
7782 CLARK 3450
7788 SCOTT 6000
7839 KING 6000
7844 TURNER 2500
7876 ADAMS 2100
7900 JAMES 1950
7902 FORD 4000
7934 MILLER 2300

PL/SQL procedure successfully completed.

Program 34: to list the names of employees in an array


DECLARE
CURSOR c_emp is
SELECT ename FROM emprd;
type c_list is varray (14) of emprd.ename%type;
name_list c_list := c_list();
counter integer :=0;
BEGIN
FOR n IN c_emp LOOP
counter := counter + 1;
name_list.extend;
name_list(counter) := n.ename;
dbms_output.put_line('Employee('||counter ||'):'||name_list(counter));
END LOOP;
END;
/
Employee(1):SMITH
Employee(2):ALLEN
Employee(3):WARD
Employee(4):JONES
Employee(5):MARTIN
Employee(6):BLAKE
Employee(7):CLARK
Employee(8):SCOTT
Employee(9):KING
Employee(10):TURNER
Employee(11):ADAMS
Employee(12):JAMES
Employee(13):FORD

K.NARESH DBMS LAB MANUAL/WORKBOOK Page 50


Employee(14):MILLER

PL/SQL procedure successfully completed.

Triggers could be defined on the table, view, schema, or database with which the event is associated.

Benefits of Triggers
Triggers can be written for the following purposes:
 Generating some derived column values automatically
 Enforcing referential integrity
 Event logging and storing information on table access
 Auditing
 Synchronous replication of tables
 Imposing security authorizations
 Preventing invalid transactions

Creating 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]
[FOR EACH ROW]
WHEN (condition)

DECLARE
Declaration-statements
BEGIN
Executable-statements
EXCEPTION
Exception-handling-statements
END;
Where,
 CREATE [OR REPLACE] TRIGGER trigger_name: Creates or replaces an existing trigger with the
trigger_name.
 {BEFORE | AFTER | INSTEAD OF} : This specifies when the trigger would be executed. The INSTEAD OF
clause is used for creating trigger on a view.
 {INSERT [OR] | UPDATE [OR] | DELETE}: This specifies the DML operation.
 [OF col_name]: This specifies the column name that would be updated.
 [ON table_name]: This specifies the name of the table associated with the trigger.
 [REFERENCING OLD AS o NEW AS n]: This allows you to refer new and old values for various DML
statements, like INSERT, UPDATE, and DELETE.
 [FOR EACH ROW]: This specifies a row level trigger, i.e., the trigger would be executed for each row being
affected. Otherwise the trigger will execute just once when the SQL statement is executed, which is called
a table level trigger.
 WHEN (condition): This provides a condition for rows for which the trigger would fire. This clause is valid
only for row level triggers.

The following program creates a row level trigger for the customers table that would fire for INSERT or
UPDATE or DELETE operations performed on the CUSTOMERS table. This trigger will display the salary
difference between the old values and new values:
CREATE OR REPLACE TRIGGER display_salary_changes
BEFORE DELETE OR INSERT OR UPDATE ON emprd
FOR EACH ROW WHEN (NEW.empno > 0)
DECLARE
sal_diff number;
BEGIN

K.NARESH DBMS LAB MANUAL/WORKBOOK Page 51


sal_diff := :NEW.sal - :OLD.sal;
dbms_output.put_line('Old salary: ' || :OLD.sal);
dbms_output.put_line('New salary: ' || :NEW.sal);
dbms_output.put_line('Salary difference: ' || sal_diff);
END;
/

When the above code is executed at SQL prompt, it produces the following result:
Trigger created.

Here following two points are important and should be noted carefully:

 OLD and NEW references are not available for table level triggers, rather you can use them for record level
triggers.
 If you want to query the table in the same trigger, then you should use the AFTER keyword, because
triggers can query the table or change it again only after the initial changes are applied and the table is
back in a consistent state.
 Above trigger has been written in such a way that it will fire before any DELETE or INSERT or UP DATE
operation on the table, but you can write your trigger on a single or multiple operations, for example
BEFORE DELETE, which will fire whenever a record will be deleted using DELETE operation on the table.

Triggering a Trigger

Let us perform some DML operations on the emprd table. Here is one INSERT statement, which will create a
new record in the table:
INSERT INTO emprd VALUES (7999,’RUPA’,’ANALYST’,7839,’23-OCT-85’,4500,100,10);

When a record is created in EMPRD table, above create trigger display_salary_changes will be fired and it will
display the following result:
Old salary:
New salary: 4500
Salary difference:

1 row created.

K.NARESH DBMS LAB MANUAL/WORKBOOK Page 52

You might also like