DBMS WorkBook
DBMS WorkBook
SQL
❖ Structured Query Language (SQL) is a language that all commercial RDBMS
implementations understand.
❖ SQL is a non-procedural language.
Naming Rules
❖ Begin with a letter and followed by zero or more of characters A-Z, 0-9, _, $, #
❖ Raw binary data, size bytes long. Maximum size is 32767 bytes RAW(size)
Constants/Literals
❖ ANSI standard defines format for literals
Operators
❖ Arithmetic operators like +,-,*,/
NULL
❖ Missing/unknown/inapplicable data represented as a null value
❖ NULL is not a data value. It is just an indicator that the value is unknown
Statements
- SQL has three flavours of statements.
DDL is Data Definition Language statements. Some examples:
▪ CREATE - to create objects in the database
▪ DELETE - deletes all records from a table, the space for the records remain
▪ SAVEPOINT - identify a point in a transaction to which you can later roll back
C/old/new 🡪 Change old to new in the current line of the current buffer. (If old is
prefixed with ‘…’ then it matches everything up to including the first
occurrence of old. If old is suffixed with ‘…’ then it matches everything
including and after the first occurrence of old.)
A text 🡪 Add text to the end of current line in current buffer.
SAVE name CREATE/ REPLACE/ APPEND 🡪 Save the content of current buffer
in to the file name. If filetype is missing, then CREATE is the default.
@filename 🡪 Run the file filename which contains SQL statements. The file may
contain any commands that may be interactively.
START file 🡪 Run the file. The file may contain any commands that may not be
interactively.
***
[Link]. 1 CREATING DATABASE TABLE Date :
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 Data Description
name type
EMPNO Number Employee number
ENAME Varchar Employee name
JOB Char Designation
MGR Number Manager’s [Link].
HIREDATE Date Date of joining
SAL Number Basic Salary
COMM Number Commission
DEPTNO Number Department Number
SQL>
SQL>
S
QL>
SQL>
Q3) List name of the tables created by the user
SQL>select * from tab;
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
▪ 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
S
QL >
SQL >
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.
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.
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>
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
Q15) Change LOC=’CHICAGO’ for deptno=30 in DEPT table and COMMIT the
transaction.
S
QL>
SQL>
▪ State of Data After ROLLBACK
o Discard all pending changes by using the ROLLBACK statement.
o Data changes are undone.
o Previous state of the data is restored.
o Locks on the affected rows are released.
Q16) Delete all the rows from EMP table and ROLLBACK the transaction.
S
QL>
SQL>
Verified by
Staff In-charge Sign : Date :
[Link]. 3 INTEGRITY CONSTRAINT Date :
S
CONSTRAINTS
▪ Constraints enforce rules at the table [Link] 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.
DEFINING CONSTRAINTS
▪ Column constraint level
column [CONSTRAINT constraint_name] constraint_type
▪ Table constraint level
[CONSTRAINT constraint_name] constraint_type(column)
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
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 [Link] column.
SQL> ALTER TABLE dept DROP PRIMARY KEY CASCADE;
DISABLE and ENABLE Constraint
▪ Execute the DISABLE clause of the ALTER TABLE statement to deactivate an
integrity constraint.
▪ Apply the CASCADE option to disable dependent integrity constraints.
▪ Activate an integrity constraint currently disabled in the table definition by using the
ENABLE clause.
A UNIQUE or PRIMARY KEY index is automatically created if you enable a
UNIQUE key or PRIMARY KEY constraint.
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 :
[Link]. 4 BASIC SELECT STATEMENTS Date :
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.
Operator Precedence
Order Operators
Evaluated
1 Parenthesis
2 All Arithmetic Operators (Multiplication and Division
followed by Addition and subtraction)
3 All Comparison Operators
4 NOT
5 AND
6 OR
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;
▪ 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
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>
Q4) List concatenated value of name and designation of each employee.
SQL>
Q5) List the names of Clerks from emp table.
SQL>
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>
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 :
Ex. No. 5 SQL FUNCTIONS Date :
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>
Q4. Date Functions
another,
producing a no.
of days
Q5. Character Functions
to format
to_char(number,’format Display Select
’)
number value as to_char(12345.5,’L099,999.99’) from
a char. dual;
to_number(char) Char string Select to_number(‘123’) from dual;
to
number form
Q7. Numeric Functions
cosine of n
Exp(n) en Select exp(2) from dual;
Floor(n) Largest int <= n Select floor(100.2) from dual;
Ln(n) Natural log of n Select ln(5) from dual;
(base e)
Log(b,n) Log n base b Select log(2,64) from dual;
Mod(m,n) Remainder of Select mod(17,3) from dual;
m
divided by n
Power(m,n) m power n Select power(5,3) from dual;
Round(m,n) m rounded to Select round(125.67854,2) from dual;
n decimal
places
Sign(n) If n<0, -1 if n=0, 0 Select sin(-19) from dual;
otherwise 1.
Sin(n) Sin of n Select sin(90) from dual;
Sinh(n) Hyperbolic sin of Select sinh(45) from dual;
n
Sqrt(n) Square root of n Select sqrt(7) from dual;
Tan(n) Tangent of n Select tan(45) from dual;
Tanh(n) Hyperbolic Select tanh(60) from dual;
tangent of n
Trunc(m,n) m truncated to n Select trunc(125.5764,2) from dual;
decimal places
Syntax :
SELECT column, group_function(column)
FROM table
[WHERE condition]
[GROUP BY group_column_or_expression]
[HAVING group_condition]
[ORDER BY column];
⮚ Columns that are not a part of the Group Functions should be included in the Group
by clause
⮚ Any column or expression in the SELECT list that is not an aggregate function must
be in the GROUP BY clause
⮚ Group Functions cannot be placed in the where clause
⮚ HAVING clause is to restrict groups Groups satisfying the HAVING condition are
displayed
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;
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 :
Ex. No. 6 JOINING TABLES Date :
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>
Joins
▪ Used to combine the data spread across tables
Syntax
SELECT [Link], [Link]
FROM table1, table2
WHERE table1.column1 = table2.column2;
▪ If join condition is omitted, then a Cartesian product is formed. That is all rows in
the first table are joined to all rows in the second table
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>
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 :
Ex. No. 7 SUB QUERIES Date :
▪ 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
Multiple-Row Subqueries
▪ Return more than one row
i
s
e
q
u
i
v
a
l
e
n
t
t
o
‘
i
n
’
‘
!
=
a
l
l
’
i
s
e
q
u
i
v
a
l
e
n
t
t
o
‘
n
o
t
i
n
’
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 ';
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 [Link], [Link], [Link], [Link]
from employee a, ( select deptno, avg(sal) salavg
from employee
group by deptno) b
where [Link] = [Link]
and [Link] > [Link];
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 [Link] = [Link]
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;
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 [Link]=mgr)
order by empno;
Verified by
Staff In-charge Sign : Date :
Ex. No. 8 VIEWS Date :
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
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;
SQL> desc empv10;
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 >
▪ You cannot remove a row/ modify data/ add data if the view contains the
following
o Group functions
o A GROUP BY clause
o The DISTINCT keyword
▪ You cannot modify data in a view if it contains columns defined by expressions or
it contains ROWNUM pseudo column
▪ You cannot add data if any NOT NULL columns in the base tables that are not
selected by the view
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>
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;
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>
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>
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 :
Ex. No. ADDITIONAL QUERIES Date :
10
Solve the queries Q1 to Q32 by considering the
following tables Table 1 : STUDIES (PNAME, SPLACE,
COURSE, CCOST)
Hint : First 3 columns are of type varchar and the 4th one is number
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>
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>
Q17) How many programmers paid 10000 to 15000 for the course?
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>
Q31) Display the costliest package developed by each programmer.
SQL>
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>
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>
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>
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>
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>
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>
QL>
SQL>
SQL>
Q67) Use these views to answer the following queries:
a. Which drivers have taken shipments to Los Angeles for customers with
revenue over $5 million?
b. What are the populations of cities which have received shipments from
customers with revenue between $1 million and $5 million?
c. Which drivers have taken shipments to cities for customers with revenue
under $1 million, and what are the populations of those cities?
QL>
SQL>
SQL>
Verified by
Staff In-charge Sign : Date :
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.
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
53
<exception
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 [Link]%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.
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;
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.
The EXIT statement forces a loop to complete unconditionally. When an EXIT
statement is encountered, the loop completes immediately and control passes to
the next statement.
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.
<<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:
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.
***
Ex. No. BASIC PL/SQL Date :
11
Q2) Write a PL/SQL Block to find the sum of odd numbers upto 100 using loop
statement
Declare
Begin
End;
/
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 [Link]%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.
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');
elsif SQL%FOUND then
num := SQL%ROWCOUNT;
dbms_output.put_line('salaries for ' || num || 'employees are updated');
end if;
End;
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.
▪ 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.
%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
The number of rows fetched by the fetch statement.
Ex. Cursor_name%ROWCOUNT
%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’.
SQL> create table emp_grade(empno number, grade
char(1)); Declare Emp_rec emp%rowtype;
Cursor c is select * into emp_rec from emp;
Begin
Open c;
If c%ISOPEN then
Loop
Fetch c into emp_rec;
If c%notfound then Exit; Endif; If
emp_rec.sal <= 1400 then
Insert into emp_grade values(emp_rec.empno,’C’);
Elsif emp_rec.sal between 1401 and 2000 then
Insert into emp_garde values(em_rec.empno,’B’);
Else
Insert into emp_garde values(em_rec.empno,’A’);
Endif
End loop;
Else
Open c;
Endif;
End;
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)
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
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.
Q14) Create a trigger which will not allow you to enter duplicate or null values in
column empno of emp table.
c
1
i
s
s
e
l
e
c
t
w
* t
y
f p
r e
o ;
m
o
e p
m e
p n
;
c
x 1
;
e
m l
p o
% o
r p
o
fetch c1 into x;
if :[Link] = [Link] then
dbms_output.put_line('you entered duplicated no');
elseif :[Link] is null then
dbms_output.put_line('you empno is null');
d
;
e
n
end; d
end if; l
e o
x o
it p
w ;
h close c1;
e
n
c
1
%
n
o
tf
o
u
n
Q15) Before Insert/Update/Delete : Statement level Trigger
Create a database trigger that allows changes to employee table only during the
business hours(i.e. from 8 a.m to 5 p.m.) from Monday to Friday. There is no
restriction on viewing data from the table
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 :
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.
▪ Integrity Constraints
▪ Transaction boundaries
Q5) SELECT PNAME, DOB FROM PROGRAMMER WHERE DOB LIKE '
%APR%';
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 [Link] = [Link]);
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