Practical Work Book of DBMS
Practical Work Book of DBMS
CONTENT
I N T R O D U C T I O N TO S Q L
SQL
v Structured Query Language (SQL) is a language that all commercial RDBMS
implementations understand.
v SQL is a non-procedural language.
v SQL is a Unified Language. It provides statements for a variety of tasks.
v Developed in a prototype relational database management System R by IBM in
mid 1970s and Oracle Corporation introduced the first commercial SQL in 1979.
Naming Rules
v Begin with a letter and followed by zero or more of characters A-Z, 0-9, _, $, #
v Not case sensitive
Data types
v Integers Decimal numbers--- NUMBER, INTEGER .
Number is an oracle data type. Integer is an ANSI data type. The syntax for
NUMBER is NUMBER(P,S) p is the precision and s is the scale. P can range
from 1 to 38 and s from -84 to +127
v Floating point numbers---- FLOAT
v Fixed length character strings---- CHAR (len)
Fixed length character data of length len bytes.
v Variable length character strings --- Varchar2(len)
Variable length character string having maximum length len bytes.
v Dates-----DATE
v Character data of variable size uo to 32760 characters --- LONG
v Raw binary data, size bytes long. Maximum size is 32767 bytes --- RAW(size)
Constants/Literals
v ANSI standard defines format for literals
v Numeric: 21, -32, $0.75,1.2E4
v String: enclosed within single quote
v Date Format : 12-mar-03
Operators
v Arithmetic operators like +,-,*,/
v Logical operators: AND, OR
v Relational operators: =,<=,>=, < >
- The Arithmetic operators are used to calculate something like given in the
example below:
Select * from employee where sal * 1.1 > 1000 ;
- The logical operators are used to combine conditions like:
Select * from employee where (sal > 1000 AND age > 25);
- The above two examples also illustrate use of relational operators
NULL
v Missing/unknown/inapplicable data represented as a null value
v NULL is not a data value. It is just an indicator that the value is unknown
Statements
- SQL has three flavours of statements.
Database Objects
v Table -- Basic unit of storage; composed of rows and columns
v View -- Logically represents subsets of data from one or more tables
v Sequence -- Generates primary key values
v Index -- Improves the performance of some queries
v Synonym -- Gives alternative names to objects
***
CREATE TABLE
ß Used to create a table by defining its structure, the data type and name of the various
columns, the relationships with columns of other tables etc.
EMP
Column name Data type Description
EMPNO Number Employee number
ENAME Varchar Employee name
JOB Char Designation
MGR Number Manager’s EMP.No.
HIREDATE Date Date of joining
SAL Number Basic Salary
COMM Number Commission
DEPTNO Number Department Number
SQL>
SQL>
SQL>
SQL>
5
Q6) View tables, views, synonyms, and sequences owned by the user
SQL> SELECT * FROM user_catalog;
ALTER TABLE
ß Add Column
ALTER TABLE table ADD(column data type [DEFAULT expr]
[, column data type]...);
ß Drop Column
ALTER TABLE table DROP column column_name;
ß Modify Column
ALTER TABLE table MODIFY(column data type [DEFAULT expr]
[, column data type]...);
Q7) Add new columns COMNT and MISCEL in DEPT table of character type.
SQL >
Q13) Remove all the rows in the table DEPT12 (Presently no records in DEPT12)
SQL >
Q14) Add some comment to the table DEPT12 and also confirm the inclusion of
comment
SQL >
SQL >
Verified by
Staff In-charge Sign : Date :
DML
ÿ A DML statement is executed when you:
• Add new rows to a table
• Modify existing rows in a table
• Remove existing rows from a table
ÿ A transaction consists of a collection of DML statements that form a logical unit of
work.
INSERT STATEMENT
ÿ Add new rows to a table by using the INSERT statement.
(i) INSERT INTO table VALUES(value1, value2,..);
ß Only one row is inserted at a time with this syntax.
ß List values in the default order of the columns in the table
ß Enclose character and date values within single quotation marks.
ß Insert a new row containing values for each column
Q2) Insert first & second rows of EMP table using syntax (ii)
SQL>
Q3) Insert the remaining rows of EMP table using syntax (iii).
SQL>
Q4) Create a table MANAGER with the columns mgr-id, name, salary and hiredate
SQL> CREATE TABLE manager(mgr-id number(5) primary key,
name varchar(20), sal number(5), hiredate date);
Q5) Insert values into the table MANAGER by copying the values from EMP table
where the designation of the employee is ‘MANAGER’
SQL> INSERT INTO manager SELECT empno,ename,sal,hiredate
FROM emp WHERE job=’MANAGER’;
UPDATE STATEMENT
ß Modify existing rows with the UPDATE statement.
ß Update more than one row at a time, if required.
ß All rows in the table are modified if you omit the WHERE clause
Q6) Change the LOC of all rows of DEPT table by ‘NEW YORK’
SQL>
DELETE STATEMENT
ß You can remove existing rows from a table by using the DELETE statement.
ß All rows in the table are deleted if you omit the WHERE clause.
Q8) Delete the rows from EMP table whose employee name = ‘PAUL’
SQL>
SELECT STATEMENT
ß To perform a query we use select statement
SELECT [DISTINCT] {*, column [alias],...}
FROM table;
Q9) List all the columns and rows of the table DEPT
SQL>
Q10) List the name of the employee and salary of EMP table
SQL>
Q11) Without duplication, list all names of the department of DEPT table.
SQL>
10
Q13) As a copy of DEPT table, create DEPT1 table using select command.
SQL> CREATE TABLE dept1 AS SELECT * FROM dept;
Q14) List ename and sal of EMP table with the column headings NAME and SALARY
SQL> SELECT ename as name, sal salary
FROM emp;
DATABASE TRANSACTIONS
ß Begin when the first executable SQL statement is executed
ß End with one of the following events:
• COMMIT or ROLLBACK
• DDL or DCL statement executes (automatic commit)
• User exits
• System crashes
Q15) Change LOC=’CHICAGO’ for deptno=30 in DEPT table and COMMIT the
transaction.
SQL>
SQL>
11
Q16) Delete all the rows from EMP table and ROLLBACK the transaction.
SQL>
SQL>
Verified by
Staff In-charge Sign : Date :
12
CONSTRAINTS
ß Constraints enforce rules at the table level.Constraints prevent the deletion of a table
if there are dependencies.
ß The following constraint types are valid in Oracle:
o NOT NULL
o UNIQUE Key
o PRIMARY KEY
o FOREIGN KEY
o CHECK
ß Name a constraint or the Oracle Server will generate a name by using the SYS_Cn
format.
ß Create a constraint:
o At the same time as the table is created
o After the table has been created
ß Define a constraint at the column or table level.
ß View a constraint in the data dictionary.
DEFINING CONSTRAINTS
ß Column constraint level
column [CONSTRAINT constraint_name] constraint_type
ß Table constraint level
[CONSTRAINT constraint_name] constraint_type(column)
Q1) Create table EMP1 with columns similar to EMP table and create NOT NULL
(column) constraint for DEPTNO column and PRIMARY KEY (table) constraint
for EMPNO column.
SQL> CREATE TABLE emp1( empno number(4),
ename varchar2(10), job char(20), mgr number(10),
hiredate date, sal number(5), comm number(5),
deptno number(7,2) NOT NULL,
CONSTRAINT emp1_pk PRIMARY KEY (empno));
13
CHECK Constraint
ÿ Defines a condition that each row must satisfy
UNIQUE Constraint
ÿ Prevent the duplication of values within the rows of a specified column
FOREIGN KEY
o Defines the column in the child table at the table constraint level
REFERENCES
o Identifies the table and column in the parent table
ON DELETE CASCADE
o Allows deletion in the parent table and deletion of the dependent rows in the
child table
ADDING A CONSTRAINT
ÿ Add or drop, but not modify, a constraint
ÿ Add a NOT NULL constraint by using the MODIFY clause
Q2) Add NOT NULL constraint to the columns ENAME and JOB of EMP table.
SQL> ALTER TABLE emp MODIFY(ename varchar2(20) NOT NULL,
job char(20) NOT NULL);
14
Q3) Add Primary key constraint to the column EMPNO of EMP table
SQL> ALTER TABLE emp ADD CONSTRAINT emp_pk
PRIMARY KEY(empno);
Q4) Add Primary key constraint to the column DEPTNO of DEPT table
SQL>
Q5) Add Unique key constraint to the column DNAME of DEPT table
SQL>
Q6) Add Check constraint to the table EMP to restrict the values of EMPNO lies
between 7000 and 8000.
SQL> ALTER TABLE emp ADD CONSTRAINT emp_ck
CHECK(empno BETWEEN 7000 AND 8000)
Q7) Add Foreign key constraint to the column DEPTNO of EMP table references
DEPTNO of DEPT table.
SQL> ALTER TABLE emp ADD CONSTRAINT emp_fk
FOREIGN KEY(deptno) REFERENCES DEPT(deptno);
Q8) Add a Foreign key constraint to the EMP1 table indicating that a manager must
already exist as a valid employee in the EMP1 table.
SQL>
DROPING CONSTRAINTS
ß Removing constraints from the table
Q9) Remove the Manager constraint (added in Q8) from EMP table
SQL>
Q10) Remove the primary key constraint on the DEPT table and drop the associated
foreign key constraint on the EMP.DEPTNO column.
SQL> ALTER TABLE dept DROP PRIMARY KEY CASCADE;
15
Q13) Query the USER_CONSTRAINTS table to view all constraint definitions and
names
SQL> SELECT constraint_name, constraint_type, search_condition
FROM user_constraints
WHERE table_name = 'EMP';
Q14) View the columns associated with the constraint names in the
USER_CONS_COLUMNS view
SQL> SELECT constraint_name, column_name
FROM user_cons_columns
WHERE table_name = 'EMP';
Verified by
Staff In-charge Sign : Date :
16
Arithmetic Operators
+ Addition
- Subtraction
* Multiplication
/ Division
Comparison Operators
= Equal to
<> Not Equal to
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
IN (List) Match any of list of values
LIKE Match a character pattern (% ‡ any no. of characters, - ‡ One Character)
IS NULL Is a null value
BETWEEN…AND… Between two values
Logical Operators
AND Returns TRUE if both component conditions are TRUE
OR Returns TRUE if either component condition is TRUE
NOT Returns TRUE if the following condition is FALSE
Concatenation Operator ( || )
ß Concatenates the Columns of any data type.
ß A Resultant column will be a Single column.
Operator Precedence
Order Evaluated Operators
1 Parenthesis
2 All Arithmetic Operators (Multiplication and Division
followed by Addition and subtraction)
3 All Comparison Operators
4 NOT
5 AND
6 OR
17
Where Clause
ß Specify the Selection of rows retrieved by the WHERE Clause
SELECT column1, column2, …
FROM table
WHERE condition;
ß The WHERE clause follows the FROM clause
Order by Clause
ß Sort rows specified by the order ASC / DESC
SELECT column1, column2, … …
FROM table
ORDER BY sort-column DESC;
ß Sorts table by sort-column in descending order
ß Omitting the keyword DESC will sort the table in ascending order
Note :
ß AS Keyword between the column name and the actual alias name
ß Date and character literal values must be enclosed within single quotation marks
ß Default date format is 'DD-MON-YY'
ß Eliminate duplicate rows by using the DISTINCT keyword
Q1) Update all the records of manager table by increasing 10% of their salary as
bonus.
SQL>
Q2) Delete the records from manager table where the salary less than 2750.
SQL>
Q3) Display each name of the employee as “Name” and annual salary as “Annual
Salary” (Note: Salary in emp table is the monthly salary)
SQL>
18
Q6) List the Details of Employees who have joined before 30 Sept 81.
SQL>
Q9) List the names of employees not belonging to dept no 30,40 & 10
SQL>
Q10) List names of those employees joined between 30 June 81 and 31 Dec 81.
SQL>
Q13) List names and designations of employee who does not report to anybody
SQL>
19
Q16) List employees whose name either start or end with ‘s’.
SQL>
Q17) List names of employees whose names have ‘i’ as the second character.
SQL>
Q18) Sort emp table in ascending order by hire-date and list ename, job, deptno and
hire-date.
SQL>
Q19) Sort emp table in descending order by annual salary and list empno, ename, job
and annual-salary. (Note : Salary in emp table is the monthly salary)
SQL>
Q20) List ename, deptno and sal after sorting emp table in ascending order by deptno
and then descending order by sal. (Note : Sorting by multiple coluns)
SQL>
Verified by
Staff In-charge Sign : Date :
20
Note : The exercises that follow mostly uses system table ‘dual’. It is a table which is
automatically created by Oracle along with the data dictionary. Dual table has one
column defined to be of varchar2 type and contains only one row with value ‘x’.
SCALAR FUNCTIONS
Q1) List the hiredate of employees who work in deptno 20 in a format like
‘WEDNESDAY JANUARY 12, 1983’
(Hint: DAY : Day of the week, MONTH : Name of the month, DD: Day of the
month, and YYYY : Year)
SQL>
Q2) Display the hiredate with time of employess who work in deptno 20.
SQL>
Q3) Each employee receives a salary review after every 150 days of service. Now list
employee name, hiredate and first salary review date of each employee who work
in dept no 20.
SQL>
21
22
23
24
GROUP FUNCTIONS
Common Group Functions
• AVG : Average value of a set
• COUNT : Numbers of non null values
• MAX : Maximum of a set
• MIN : Minimum of a set
• STDDEV : Standard Deviation of a set
• SUM : Sum of a set
• VARIANCE : Variance of a set
Syntax :
SELECT column, group_function(column)
FROM table
[WHERE condition]
[GROUP BY group_column_or_expression]
[HAVING group_condition]
[ORDER BY column];
25
Q17) List the department numbers and number of employees in each department
SQL>
Q18) List the jobs and number of employees in each job. The result should be in the
descending order of the number of employees.
SQL> select job, count(*) from emp
group by job
order by count(*) desc;
26
Q19) List the total salary, maximum and minimum salary and average salary of the
employees jobwise.
SQL>
Q20) List the total salary, maximum and minimum salary and average salary of the
employees jobwise, for department 20 and display only those rows having an
average salary > 1000.
SQL> select job,sum(sal), max(sal), min(sal), avg(sal)
from emp
group by job, deptno
having deptno=20 and avg(sal) > 1000;
Q21) List the job and total salary of employees jobwise, for jobs other than
‘PRESIDENT’ and display only those rows having total salary > 5000.
SQL>
Q22) List the job, number of employees and average salary of employees jobwise.
Display only the rows where the number of employees in each job is more than
two.
SQL>
Verified by
Staff In-charge Sign : Date :
27
Set operators
ß Set operators combine the results of two queries into a single.
Operator Function
Union Returns all distinct rows selected by either query
Union all Returns all rows selected by either query including duplicates
Intersect Returns only rows that are common to both the queries
Minus Returns all distinct rows selected only by the first query and not
by the second.
SQL>
SQL>
Q2) List the names of distinct customers who have either loan or account
SQL>
Q3) List the names of customers (with duplicates) who have either loan or account
SQL> (select cus_name from borrower)
union all (select cus_name from depositor)
Q4) List the names of customers who have both loan and account
SQL>
Q5) List the names of customers who have loan but not account
SQL>
28
Joins
ß Used to combine the data spread across tables
Syntax
SELECT table1.column, table2.column
FROM table1, table2
WHERE table1.column1 = table2.column2;
Types of Joins
ß Inner Join (Simple Join) : It retrieves rows from 2 tables having a common column.
o Equi Join : A join condition with relationship = .
o Non Equi Join : A join condition with relationship other than = .
ß Self Join : Joining of a table to itself
ß Outer Join : Returns all the rows returned by simple join as well as
those rows from one table that do not match any row from
the other table. The symbol (+) represents outer joins.
Q6) List empno, ename, deptno from emp and dept tables.
SQL>
29
Q8) List ename, deptno and deptname from emp and dept tables, including the rows of
emp table that does not match with any of the rows in dept table.
SQL>
Q9) List ename, deptno and deptname from emp and dept tables, including the rows of
dept table that does not match with any of the rows in emp table.
SQL>
Q10) List the names of the employee with name of his/her manager from emp table.
SQL>
Verified by
Staff In-charge Sign : Date :
30
Syntax
SELECT select_list
FROM table
WHERE expr operator ( SELECT select_list
FROM table);
ß The subquery (inner query) executes once before the main query.
ß The result of the subquery is used by the main query (outer query).
Single-Row Subqueries
ß Return only one row
ß Use single-row comparison operators (ie; relational operators)
Multiple-Row Subqueries
ß Return more than one row
ß Use multiple-row comparison operators
Operator Meaning
IN Equal to any member in the list
ANY Compare value to each value returned by the subquery
ALL Compare value to every value returned by the subquery
Note:
‘=any’ is equivalent to ‘in’
‘!=all’ is equivalent to ‘not in’
31
Q1) List the name of the employees whose salary is greater than that of employee with
empno 7566.
SQL> select ename from employee
where sal > (select sal from employee
where empno=7566);
Q2) List the name of the employees whose job is equal to the job of employee with
empno 7369 and salary is greater than that of employee with empno 7876.
SQL>
Q3) List the ename,job,sal of the employee who get minimum salary in the company.
SQL> select ename, job, sal from employee
where sal = (select min(sal) from employee);
Q4) List deptno & min(salary) departmentwise, only if min(sal) is greater than the
min(sal) of deptno 20.
SQL> select deptno, min(sal) from employee
group by deptno
having min(sal) > (select min(sal) from employee
where deptno = 20);
Q5) List empno, ename, job of the employees whose job is not a ‘CLERK’ and whose
salary is less than at least one of the salaries of the employees whose job is
‘CLERK’.
SQL> select empno, ename, job from employee
where sal < any (select sa from employee
where job = 'CLERK')
and job <> ' CLERK ';
32
Q6) List empno, ename, job of the employees whose salary is greater than the average
salary of each department.
SQL>
Q7) Display the name, dept. no, salary, and commission of any employee whose
salary and commission matches both the commission and salary of any employee
in department 30.
SQL> select ename, deptno, sal, comm
from employee
where (sal, nvl(comm,-1)) in ( select sal, nvl(comm,-1)
from employee
where deptno = 30);
Q8) List ename sal, deptno, average salary of the dept where he/she works, if salary
of the employee is greater than his/her department average salary.
SQL> select a.ename, a.sal, a.deptno, b.salavg
from employee a, ( select deptno, avg(sal) salavg
from employee
group by deptno) b
where a.deptno = b.deptno
and a.sal > b.salavg;
Q9) Execute and Write the output of the following query in words.
SQL> with summary as
(select dname,sum(sal) as dept_total from employee a , department b
where a.deptno = b.deptno
group by dname);
select dname,dept_total from summary
where dept_total > (select sum(dept_total)*1/3 from summary)
order by dept_total desc;
33
Q10) List ename, job, sal of the employees whose salary is equal to any one of the
salary of the employee ‘SCOTT’ and ‘WARD’.
SQL>
Q11) List ename, job, sal of the employees whose salary and job is equal to the
employee ‘FORD’.
SQL>
Q12) List ename, job, deptno, sal of the employees whose job is same as ‘JONES’ and
salary is greater than the employee ‘FORD’.
SQL>
Q13) List ename, job of the employees who work in deptno 10 and his/her job is any
one of the job in the department ‘SALES’.
SQL>
Q14) Execute the following query and write the result in word
SQL> select job,ename,empno,deptno from emp s
where exists (select * from emp
where s.empno=mgr)
order by empno;
Verified by
Staff In-charge Sign : Date :
34
VIEWS
ß An Imaginary table contains no data and the tables upon which a view is based are
called base tables.
ß Logically represents subsets of data from one or more tables
Advantages of view
ß To restrict database access
ß To make complex queries easy
ß To allow data independence
ß To present different views of the same data
Syntax
CREATE [OR REPLACE] VIEW view [col1 alias, col2 alias,...]
AS subquery
[ WITH CHECK OPTION [ CONSTRAINT constraint ] ]
[ WITH READ ONLY ]
Q1) Create a view empv10 that contains empno, ename, job of the employees who
work in dept 10. Also describe the structure of the view.
SQL> create view empv10 as
select empno, ename, job from emp
where deptno=10;
Q2) Create a view with column aliases empv30 that contains empno, ename, sal of the
employees who work in dept 30. Also display the contents of the view.
SQL >
35
Q3) Update the view empv10 by increasing 10% salary of the employees who work as
‘CLERK’. Also confirm the modifications in emp table.
SQL > update empv10 set sal = sal+0.10*sal
where job=’CLERK’;
Q4) Modify the view empv10 which contains the data empno, ename, job, sal. Add an
alias for each column name.
SQL > create or replace view empv10
(employee_no, employee_name, job, salary) as
select empno, ename, job,sal from emp where deptno=10;
Q5) Using emp table, create a view pay which contains ename, monthly_sal,
annual_sal, deptno.
SQL>
Q6) Create a view dept_stat which contains department no., department name,
minimum salary, maximum salary, total salary.
SQL>
36
Q7) Execute the following query and then try to delete the row with dept no 20. Now
write in words that you understand
SQL> create or replace view empv20
as select * from emp where deptno = 20
with check option constraint empv20_ck;
Q8) Create a view empv10 with all the details of employees who work in dept no. 10.
Also ensure that no DML operations can be done with the view.
SQL> create or replace view empv10
as select * from emp where deptno = 20
with read only;
Deleting Views
Syntax
DROP VIEW view_name;
37
Q4) Get all Supplyno/Partno/Jobno triples such that all are co-located.
SQL>
Q5) Get al Supplyno, Partno, Jobno triples such that they are not all co-located.
SQL>
Q7) Get all pairs of cities such that a supplier in the first city supplies to a Project in
the second city.
SQL>
38
Q8) Get Jobno for projects supplied by at least one supplier not in the same city.
SQL>
Q9) Get all pairs of part numbers such that some supplier supplies both the indicated
parts.
SQL>
Q11) For each part supplied to a project, get the Partno, Jobno and corresponding total
quantity.
SQL>
Q12) Get Partno of parts supplied to some project in an average quantity > 320.
SQL>
Q15) Get Jobno for projects using at least one part available from supplier S1.
SQL>
Q16) Get supplier numbers for suppliers supplying at least one part supplied by at least
one supplier who supplies at least one red part.
SQL>
39
Q17) Get supplier numbers for suppliers with a status lower than that of supplier S1.
SQL>
Q18) Get project numbers for projects not supplied with any red part by any London
supplier.
SQL>
Verified by
Staff In-charge Sign : Date :
40
LEGEND :
PNAME – Programmer Name, SPLACE – Study Place, CCOST – Course Cost,
DEVIN – Developed in, SCOST – Software Cost, DCOST – Development Cost,
PROF1 – Proficiency 1
Q1) Find out the selling cost average for packages developed in Oracle.
SQL>
Q3) Display the names of those who have done the PGDCA course.
SQL>
Q5) Display the names and date of birth of all programmers born in April.
SQL>
41
Q8) How much revenue has been earned through the sale of packages developed in C.
SQL>
Q11) Display the details of packages whose sales crossed the 5000 mark.
SQL>
Q12) Find out the number of copies which should be sold in order to recover the
development cost of each package.
SQL>
Q13) Display the details of packages for which the development cost has been
recovered.
SQL>
42
Q17) How many programmers paid 10000 to 15000 for the course?
SQL>
43
Q24) Calculate the experience in years for each programmer and display along with
their names in descending order.
SQL>
Q25) Who are the programmers who celebrate their birthdays during the current
month?
SQL>
Q30) Display the details of those who don’t know C, C++ or Pascal.
SQL>
44
Q32) Produce the following output for all the male programmers
Programmer
Mr. Arvind – has 15 years of experience
SQL>
Solve Queries from Q33 to 47 using the table dept and emp.
Q33) List all the employees who have at least one person reporting to them.
SQL>
Q34) List the employee details if and only if more than 10 employees are present in
department no 10.
SQL>
Q35) List the name of the employees with their immediate higher authority.
SQL>
Q36) List all the employees who do not manage any one.
SQL>
45
Q37) List the employee details whose salary is greater than the lowest salary of an
employee belonging to deptno 20.
SQL>
Q38) List the details of the employee earning more than the highest paid manager.
SQL>
Q41) In which year did most people join the company? Display the year and the
number of employees.
SQL>
Q43) Write a query to display a ‘*’ against the row of the most recently hired
employee.
SQL>
46
Q44) Write a correlated sub-query to list out the employees who earn more than the
average salary of their department.
SQL>
Q46) Select the duplicate records (Records, which are inserted, that already exist) in the
EMP table.
SQL>
Q47) Write a query to list the length of service of the employees (of the form n years
and m months).
SQL>
SQL>
47
SQL>
Q49) What are the names of customers who have sent packages (shipments) to Sioux
City?
SQL>
Q50) To what destinations have companies with revenue less than $1 million sent
packages?
SQL>
Q51) What are the names and populations of cities that have received shipments
weighing over 100 pounds?
SQL>
Q52) Who are the customers having over $5 million in annual revenue who have sent
shipments weighing less than 1 pound?
SQL>
48
Q53) Who are the customers having over $5 million in annual revenue who have sent
shipments weighing less than 1 pound or have sent a shipment to San Francisco?
SQL>
Q54) Who are the drivers who have delivered shipments for customers with annual
revenue over $20 million to cities with populations over 1 million?
SQL>
Q55) List the cities that have received shipments from customers having over $15
million in annual revenue.
SQL>
Q56) List the names of drivers who have delivered shipments weighing over 100
pounds.
SQL>
Q57) List the name and annual revenue of customers who have sent shipments
weighing over 100 pounds.
SQL>
Q58) List the name and annual revenue of customers whose shipments have been
delivered by truck driver Jensen.
SQL>
Q59) List customers who had shipments delivered by every truck. ( use NOT EXISTS)
SQL>
Q60) List cities that have received shipments from every customer. ( use NOT
EXISTS)
SQL>
49
Q61) List drivers who have delivered shipments to every city. (use NOT EXISTS)
SQL>
Q62) Customers who are manufacturers or have sent a package to St. Louis.
SQL>
Q63) Cities of population over 1 million which have received a 100-pound package
from customer 311.
SQL>
Q64) Trucks driven by Jake Stinson which have never delivered a shipment to Denver.
SQL>
Q65) Customers with annual revenue over $10 million which have sent packages under
1 pound to cities with population less than 10,000.
SQL>
SQL>
SQL>
50
SQL>
SQL>
SQL>
Verified by
Staff In-charge Sign : Date :
51
PL/SQL INTRODUCTION
PL/SQL
ß PL/SQL bridges the gap between database technology and procedural programming
languages.
ß PL/SQL uses the facilities of the sophisticated RDBMS and extends the standard SQL
database language
ß Not only PL/SQL allow you to insert, delete, update and retrieve data, it lets you use
procedural techniques such as looping and branching to process the data.
ß Thus PL/SQL provides the data manipulating power of SQL with the data processing
power of procedural languages
Advantage of PL/SQL
PL/SQL is a completely portable, high performance transaction processing language. It
provides the following advantages :
ß Procedural Capabilities
o It supports many of constructs like constants, variable, selection and
iterative statements
ß Improved Performance
o Block of SQL statements can be executed at a time
ß Enhanced Productivity
o PL/SQL brings added functionality to non procedural tools such as
SQL Forms.
ß Portability
o PL/SQL can run anywhere the RDBMS can run
ß Integration with RDBMS
o Most PL/SQL variables have data types native to the RDBMS data
dictionary. Combined with the direct access to SQL, these native data
type declarations allow easy integration of PL/SQL with RDBMS.
Character Set
It is either ASCII or EBCDIC format
Identifiers
It begins with a letter and can be followed by letters, numbers, $ or #. Maximum
size is 30 characters in length.
52
Variable Declaration
The data types (number, varchar2, real, date, …) discussed in SQL are all
applicable in PL/SQL.
Ex. Salary Number(7,2);
Sex Boolean;
Count smallint :=0;
Tax number default 750;
Name varchar2(20) not null;
Constant declaration
Ex. Phi Constant Number(7,2) := 3.1417;
Comment
Line can be commented with double hyphen at the beginning of the line.
Ex. - - This is a comment line
Assignments
Variable assignment sets the current value of a variable. You can assign values to
a variable as follows
(i) Assignment operator (:=)
Ex. d := b*b – 4*a*c;
(ii) Select … into statement
Ex. Select sal into salary from emp where empno=7655;
Operators
Operators used in SQL are all applicable to PL/SQL also.
Block Structure
PL/SQL code is grouped into structures called blocks. If you create a stored procedure or
package, you give the block of PL/SQL code a name. If the block of PL/SQL code is not
given a name, then it is called an anonymous block.
The PL/SQL block divided into three section: declaration section, the executable
section and the exception section
The structure of a typical PL/SQL block is shown in the listing:
declare
< declaration section >
begin
< executable commands>
exception
<exception handling>
end;
53
Declaration Section :
Defines and initializes the variables and cursor used in the block
Executable commands :
Uses flow-control commands (such as IF command and loops) to execute the
commands and assign values to the declared variables
Exception handling :
Provides handling of error conditions
The %TYPE attribute is particularly useful when declaring variables that refer to
database columns. You can reference a table and column, or you can reference an
owner, table, and column.
my_dname dept.dname%TYPE;
DECLARE
emp_rec emp%ROWTYPE;
...
BEGIN
SELECT * INTO emp_rec FROM emp WHERE ...
...
END;
Columns in a row and corresponding fields in a record have the same names and
data types.
54
The column values returned by the SELECT statement are stored in fields. To
reference a field, you use the dot notation.
DECLARE
dept_rec1 dept%ROWTYPE;
dept_rec2 dept%ROWTYPE;
…..
BEGIN
.. …..
dept_rec1 := dept_rec2;
…..
END;
Second, you can assign a list of column values to a record by using the SELECT
and FETCH statement, as the example below shows. The column names must
appear in the order in which they were defined by the CREATE TABLE or
CREATE VIEW statement.
DECLARE
dept_rec dept%ROWTYPE;
….
BEGIN
SELECT deptno, dname, loc INTO dept_rec FROM dept
WHERE deptno = 30;
….
END;
55
Note : Give absolute path of the filename if you saved the file in some directory.
Ex. SQL> start z:\plsql\ex11; (or) SQL> @ z:\plsql\ex11;
Control Structures
(i) IF Statements
There are three forms of IF statements: IF-THEN, IF-THEN-ELSE, and IF-
THEN-ELSIF. The third form of IF statement uses the keyword ELSIF (NOT
ELSEIF) to introduce additional conditions, as follows:
IF condition1 THEN
sequence_of_statements1;
ELSIF condition2 THEN
sequence_of_statements2;
ELSE
sequence_of_statements3;
END IF;
LOOP
The simplest form of LOOP statement is the basic (or infinite) loop, which
encloses a sequence of statements between the keywords LOOP and END LOOP,
as follows:
LOOP
sequence_of_statements3;
...
END LOOP;
With each iteration of the loop, the sequence of statements is executed, then
control resumes at the top of the loop. If further processing is undesirable or
impossible, you can use the EXIT statement to complete the loop. You can place
one or more EXIT statements anywhere inside a loop, but nowhere outside a loop.
There are two forms of EXIT statements: EXIT and EXIT-WHEN.
56
LOOP
...
IF ... THEN
...
EXIT; -- exit loop immediately
END IF;
END LOOP;
-- control resumes here
LOOP
….
EXIT WHEN i>n; -- exit loop if condition is true
….
END LOOP;
….
Until the condition evaluates to TRUE, the loop cannot complete. So, statements
within the loop must change the value of the condition.
Like PL/SQL blocks, loops can be labeled. The label, an undeclared identifier
enclosed by double angle brackets, must appear at the beginning of the LOOP
statement, as follows:
<<label_name>>
LOOP
sequence_of_statements;
...
END LOOP [label_name];
Optionally, the label name can also appear at the end of the LOOP statement.
With either form of EXIT statement, you can complete not only the current loop,
but any enclosing loop. Simply label the enclosing loop that you want to
complete, then use the label in an EXIT statement.
57
<<outer>>
LOOP
...
LOOP
...
EXIT outer WHEN ... -- exit both loops
END LOOP;
...
END LOOP outer;
(iii) WHILE-LOOP
The WHILE-LOOP statement associates a condition with a sequence of
statements enclosed by the keywords LOOP and END LOOP, as follows:
Before each iteration of the loop, the condition is evaluated. If the condition
evaluates to TRUE, the sequence of statements is executed, then control resumes
at the top of the loop. If the condition evaluates to FALSE or NULL, the loop is
bypassed and control passes to the next statement. Since the condition is tested at
the top of the loop, the sequence might execute zero times.
(iv) FOR-LOOP
Whereas the number of iteration through a WHILE loop is unknown until the loop
completes, the number of iterations through a FOR loop is known before the loop
is entered. FOR loops iterate over a specified range of integers. The range is part
of an iteration scheme, which is enclosed by the keywords FOR and LOOP.
The lower bound need not be 1. However, the loop counter increment (or
decrement) must be 1. PL/SQL lets you determine the loop range dynamically at
run time, as the following example shows:
58
The loop counter is defined only within the loop. You cannot reference it outside
the loop. You need not explicitly declare the loop counter because it is implicitly
declared as a local variable of type INTEGER.
The EXIT statement allows a FOR loop to complete prematurely. You can
complete not only the current loop, but any enclosing loop.
BEGIN
...
GOTO insert_row;
...
<<insert_row>>
INSERT INTO emp VALUES ...
END;
The NULL statement explicitly specifies inaction; it does nothing other than pass
control to the next statement. It can, however, improve readability. Also, the
NULL statement is a handy way to create stubs when designing applications
from the top down.
***
59
Declare
a number;
b number;
c number;
Begin
dbms_output.put_line('Enter a:');
a:=&a;
dbms_output.put_line('Enter b:');
b:=&b;
dbms_output.put_line('Enter c:');
c:=&c;
if (a>b) and (a>c) then
dbms_output.putline('A is Maximum');
elsif (b>a) and (b>c) then
dbms_output.putline('B is Maximum');
else
dbms_output.putline('C is Maximum');
end if;
End;
/
Q2) Write a PL/SQL Block to find the sum of odd numbers upto 100 using loop
statement
Declare
Begin
End;
/
60
Q3) Write a PL/SQL block to get the salary of the employee who has empno=7369
and update his salary as specified below
- if his/her salary < 2500, then increase salary by 25%
- otherwise if salary lies between 2500 and 5000, then increase
salary by 20%
- otherwise increase salary by adding commission amount to the
salary.
Declare
Salary number(5);
Begin
Select sal into salary from emp where empno=7369;
-- complete remaining statements
End;
/
Q4) Write a PL/SQL Block to modify the department name of the department 71 if it
is not ‘HRD’.
Declare
deptname dept.dname%type;
Begin -- complete the block
End;
/
CURSOR
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.
61
There are two types of cursors in PL/SQL. They are Implicit cursors and Explicit
cursors.
Implicit cursors
These are created by default when DML statements like, INSERT, UPDATE, and
DELETE statements are executed.
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.
%FOUND
The return value is TRUE, if the DML statements like INSERT, DELETE
and UPDATE affect at least one row or if SELECT ….INTO statement
return at least one row. Ex. SQL%FOUND
%NOTFOUND
The return value is FALSE, if DML statements affect at least one row or if
SELECT. …INTO statement return at least one row.
Ex. SQL%NOTFOUND
%ROWCOUNT
Return the number of rows affected by the DML operations
Ex. SQL%ROWCOUNT
Q5) Write a PL/SQL Block, to update salaries of all the employees who work in
deptno 20 by 15%. If none of the employee’s salary are updated display a
message 'None of the salaries were updated'. Otherwise display the total number
of employee who got salary updated.
Declare
num number(5);
Begin
update emp set sal = sal + sal*0.15 where deptno=20;
if SQL%NOTFOUND then
dbms_output.put_line('none of the salaries were updated');
62
Explicit cursors
They must be created when you are executing a SELECT statement that returns
more than one row. Even though the cursor stores multiple records, only one
record can be processed at a time, which is called as current row. When you fetch
a row the current row position moves to next row.
Fetching Cursor :
FETCH cursor_name INTO variable-list/record-type;
%FOUND
TRUE, if fetch statement returns at least one row.
Ex. Cursor_name%FOUND
%NOTFOUND
TRUE, , if fetch statement doesn’t return a row.
Ex. Cursor_name%NOTFOUND
%ROWCOUNT
63
%ISOPEN
TRUE, if the cursor is already open in the program.
Ex. Cursor_name%ISOPEN
Q6) Create a table emp_grade with columns empno & grade. Write PL/SQL block to
insert values into the table emp_grade by processing emp table with the following
constraints.
If sal <= 1400 then grade is ’C’
Else if sal between 1401 and 2000 then the grade is ‘B’ Else the grade is ‘A’.
64
Q8) Write a PL/SQL block to find the name and salary of first five highly paid
employees.
65
Q10) Write a PL/SQL block to find the names of employees & job and total number of
employees who have more than 28 years of service in the company.(Use for loop)
66
II. TRIGGER
A trigger is a PL/SQL block structure which is fired when DML statements like Insert,
Delete and Update is executed on a database table. A trigger is triggered automatically
when an associated DML statement is executed.
Syntax of Trigger
67
Types of Triggers
There are two types of triggers based on which level it is triggered.
ß Row level trigger : An event is triggered for each row updated, inserted or deleted.
ß Statement level trigger : An event is triggered for each SQL statement executed.
Before and After Triggers : Since triggers occur because of events, they may be set to
occur immediately before or after those events. Within the trigger, we are able to
refer old and new values involved in transactions. Old refers to the data as it existed
prior to the transaction. New refer to the data that the transaction creates.
68
Q14) Create a trigger which will not allow you to enter duplicate or null values in
column empno of emp table.
69
We can use the data dictionary 'USER_TRIGGERS' to obtain information about any
trigger. The below statement shows the structure of 'USER_TRIGGERS'.
SQL> desc user_triggers;
Q16) Find the trigger type, trigger event and table name of the trigger ‘time_check’.
SQL> select trigger_type, trigger_event, table_name
from user_triggers where trigger_name = ‘TIME_CHECK’;
Verified by
Staff In-charge Sign : Date :
70
APPENDIX -A
CODD’S RULES
Codd’s rule provides a method for therotical evalution of a product, that claims to be a
Relational Data Base Management System.
71
User access to the database via terminal monitors or application programs must remain
logically consistent whenever changes to the storage representation or access methods to
the data are changed.
72
APPENDIX -B
Q5) SELECT PNAME, DOB FROM PROGRAMMER WHERE DOB LIKE '
%APR%';
73
74
Q34) SELECT * FROM EMP WHERE DEPTNO IN (SELECT DEPTNO FROM EMP
GROUP BY DEPTNO HAVING COUNT(EMPNO)>10 AND DEPTNO=10);
Q36) SELECT * FROM EMP WHERE EMPNO IN ( SELECT EMPNO FROM EMP
MINUS SELECT MGR FROM EMP);
Q37) SELECT * FROM EMP WHERE SAL > ( SELECT MIN(SAL) FROM EMP
GROUP BY DEPTNO HAVING DEPTNO=20);
Q38) SELECT * FROM EMP WHERE SAL > ( SELECT MAX(SAL) FROM EMP
GROUP BY JOB HAVING JOB = 'MANAGER' );
Q44) SELECT ENAME,SAL FROM EMP E WHERE SAL > (SELECT AVG(SAL)
FROM EMP F WHERE E.DEPTNO = F.DEPTNO);
Q45) SELECT ENAME, SAL FROM EMP A WHERE &N = (SELECT COUNT
(DISTINCT(SAL)) FROM EMP B WHERE A.SAL<=B.SAL);
75
76
77
78
BIBLIOGRAPHY
The following books and manuals were referred during the preparation of this work book
and suggested for further reading
ß Date C.J, “An Introduction to Database”, 8th Edition , 2003, Addison-Wesley Pub
Co, ISBN: 978-0321197849
79