Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 83

Normalization It is defined as process of query optimization or it is also defined as a process of

table refinement. In normalization we verify tables with different rules and if table doesn’t
satisfy a rule then we decompose the table into more tables and hence it is also defined as a
process of table decomposition. It is dependent on a concept called as functional dependency.

Functional Dependency It is stated as if there is a dominant key in a table which is normally


called a primary key, which determines every row (tuple) uniquely, ie every other column in the
table must be fully dependent on primary key. It is also defined mathematically as follows

For every F.D X -> Y is said to hold true if and only if there exist t1,t2 in X s.t if t1(X) = t2(X)
then t1(Y) = t2(Y) should also be true.
For eg consider a table Employee with columns as
Empid, fname, mname, lname, city, state
1 x y z Mumbai MH
2 a b c Thane MH
1 e f g Mumbai MH
X ={Empid}
Values={{1},{2},{1}}
Y={fname, mname, lname, city, state}
Values={{x,y,z,Mumbai,MH},{a,b,c,Thane,MH},{e,f,g,Mumbai,MH}}
In 1st and 2nd row t1(X) ≠t2(X) and hence t1(Y) may be equal or not equal to t2(Y)
In 1st and 3rd row t1(X) = t3(X) but t1(Y)≠t3(Y) hence FD is not holding true so for the table to
satisfy FD it must be changed as follows
Empid, fname, mname, lname, city, state
1 x y z Mumbai MH
2 a b c Thane MH
1 x y z Mumbai MH
Now it is satisfying FD.
Normalization procedure consist of different normal forms which are also referred as rules given
as follows
1NF -> 1st Normal From
2NF -> 2nd Normal From
3NF -> 3rd Normal Form
BCNF - > Boyce Codd Normal Form
4NF - > 4th Normal Form
5NF - > 5th Normal Form
These normal forms are hierarchical as for a table to be in higher normal form it has to be in
lower normal form. For eg if a table is in 3rd NF it means that table is also in 2nd NF and 1st NF.
1st Normal Form: A table is said to be in 1NF iff there are no multi valued attributes.
Consider an example called employee table as follows
Employee
emp_id, emp_name, emp_city, emp_dep_name
Consider an employee having one dependent, another employee with 2 dependents and another
employee with 3 dependents, Now as for employee with one dependent is concerned can be
stored in one row but with 2 & 3 dependents will require 2 & three rows respectively as follows
emp_id, emp_name, emp_city, emp_dep_name
1 a Mumbai O
2 b Thane P
Q
3 c Mumbai R
S
T
Employee no 2 & 3 are having 2 & three dependents which requires additional rows which adds
redundancy in the table as corresponding values in other rows of such employees will remain
blank which is called NULL values and hence this table doesn’t satisfy 1 st NF, Thus to make this
table satisfy 1st NF it must be broken down into more tables as follows
Employee
emp_id, emp_name, emp_cit
1 a Mumba
2 b Thane
3 c Mumba
Employee_Dep
emp_id, emp_dep_name
1 O
2 P
2 Q
3 R
3 S
3 T
2/7/2021
SQL-STRUCTURED QUERY LANGUAGE

1972 DR. CODD GAVE ER MODELLING, RELATIONAL MODELLING, RELATIONAL


ALGEBRA, REALTIONAL CALCULUS, USING RELATIONAL ALGEBRA IBM
DESIGNED SEQUEL IN 1975, WHERE SEQUEL - SEQUENTIAL ENGLISH LIKE QUERY
LANGUAGE

SEQUEL RENAMED AS SQL IN 1982 BY ANSI-ISO COMMITTEE


ANSI-ISO COMM. REVISED SQL AS SQL1 1986
SQL1 AGAIN REVISED IN 1989 AS RDBMS

SQL2 IN 1992 AS RDBMS


SQL3 IN 1999 AS OODBMS USED OBJECT ORIENTED PROGRAMMING

SQL4 IN 2004 AS ORDBMS

SQL IS A LANGUAGE WHICH CONSIST SUBLANGUAGES


1 DDL
2 DML
DDL -DATA DEFINITION LANGUAGE WHICH CONSIST OF THE STATEMENTS SUCH
AS
CREATE TABLE
CREATE USER
CREATE ASSERTION
CREATE SYNONYM
CREATE TRIGGER
CREATE VIEW etc
DROP STATEMENT CAN BE USED TO REMOVE ABOVE CREATED OBJECTS.
ALTER STATEMENT CAN BE USED MODIFY ABOVE CREATED OBJECTS
GRANT STATEMENT USED TO ASSIGN RIGHTS (PRIVILEGES) TO USERS SUCH AS
SELECT, INSERT DELETE UPDATE ETC.
REVOKE STATEMENT USED TO RMOVE RIGHTS FROM USERS

DML HAS FURTHER SUB LANGUAGES WHICH ARE


DQL DATA QUERY LANGUAGE
SELECT, INSERT, DELETE, UPDATE
DTL DATA TRANSACTION LANGUAGE
BEGIN, COMMIT, ROLLBACK, SAVE
SOMETIMES GRANT & REVOKE IS NAMED AS DCL -DATA CONTROL
LANGUAGE(DDL)

2/7/2021

CREATE

HOW TO CREATE A USER?


CREATE USER USERNAME
IDENTIFIED BY PASSWORD;
CREATE, USER, IDENTIFIRED BY ARE KEYWORDS &USERNAME, PASSWORD USER
DEFINED NAMES

EG. CREATE USER 19001REEYA


IDENTIFIED BY RYA001; O/P USER CREATED
GRANT ALL PRIVILEGES TO 19001REEYA; PRIVILEGES LIKE CREATE, SELECT,
INSERT, DELETE ETC WILL BE ALLOTED TO USER.

AFTER USER IS CREATED USER CAN LOG IN INTO ACOUNT AND EXECUTE
QUERIES.

ABOVE USER CAN BE CREATED BY LOG IN ADMIN ACCOUNT, WHERE ADMIN


ACCOUNT IS TO BE SET WHILE INSTALLING ORACLE, THE ADNIN USERNAME
TAKEN BY ORACLE IS SYSTEM OR SYS AND THE PASSWORD HAS TO SELECTED
DURING INSTALATION.

ALSO ORACLE CRAETES A DEFAULT USER FOR EXECUTING QUERIES WHICH IS


SCOTT AND PASSWORD IS TIGER.

CREATING TABLES SYNTAX:

CREATE TABLE TABLENAME


(
COLUMN_NAME1 DATA_TYPE CONSTRAINT(OPTIONAL),
COLUMN_NAME2 DATA_TYPE " ,
. ,
.
.
LAST_COLUMN_NAME DATA_TYPE "
);
CREARTE TABLE-KEYWORD REST ALL ARE USER DEFINED NAMES ALONG WITH
SOME MORE KEYWORDS FOR DATA TYPE AND CONSTRAINT.
SOME DATA TYPES ARE
INTEGER, CHAR(), VARCHAR() OR VARCHAR2(), NUMBER(), DATE, TIME ETC..
CHAR() - CHARACTER ARRAY.
VARCHAR() OR VARCHAR2()-VARIABLE LENGTH CHARACTER ARRAY.
CHAR(10) IT WILL RESERVE ALL 10 SPACES WHETHER ACTUALLY USED OR NOT.
VARCHAR(10) IT WILL RESERVE ONLY THE NEEDED NO OF CHARACTERS.
VARCHAR() IS ALSO CALLED VARCHAR2() AS IT WAS ADDED IN SQL2.
EG. TABLE
EMPLOYEE( EMPID(PK), FNAME, MNAME, LNAME, SALARY, CITY, PIN, DID(FK))
DEPARTMENT(DEPTID(PK), DNAME, DEPTBGT, DEPTLOC)

03/7/2021
CREATE TABLE DEPARTMENT
(
DEPTID NUMBER(4) PRIMARY KEY,
DNAME VARCHAR2(15),
DEPTBGT NUMBER(10),
DEPTLOC VARCHAR2(15)
);

CREATE TABLE EMPLOYEE


(
EMPID INTEGER PRIMARY KEY,
FNAME VARCHAR2(10),
MNAME VARCHAR(10),
LNAME VARCHAR(10),
SALARY NUMBER(7),
CITY VARCHAR2(20),
PIN NUMBER(6),
DID NUMBER(4) FOREIGN KEY REFERENCES DEPARTMENT
);

ADD A COLUMN IN TABLE DEPARTMENT AS MANAGER

ALTER TABLE DEPARTMENT


ADD COLUMN MANAGER NUMBER(4);

TO REMOVE DEPTLOC FROM DEPARTMENT TABLE

ALTER TABLE DEPARTMENT


DROP COLUMN DEPTLOC;

03/7/2021

AGIAN I WANT TO ADD COLUMN DEPTLOC IN DEPARTMENT

ALTER TABLE DEPARTMENT


ADD COLUMN DEPTLOC VARCHAR2(15);

CONSIDER 2 MORE TABLE NAMELY

ORDERS(OID(PK), ODATE, AMOUNT, PID(FK))


PRODUCTS(PRID(PK),PNAME, PRICE)
NOTE: IF WE CREATED THE TABLE HAVING FK BEFORE AND THE TABLE WITH
CORRESPONDING PK LATERTHEN WHAT TO DO

CREATE TABLE ORDERS


(
OID NUMBER(4) PRIMARY KEY,
ODATE DATE,
AMOUNT NUMBER(15,2),
PID NUMBER(4)
);

CREATE TABLE PRODUCTS


(
PRID NUMBER(4) PRIMARY KEY,
PNAME VARCHAR2(20),
PRICE NUMBER(10,2)
);

ALTER TABLE ORDERS


ADD CONSTRAINT FK1 FOREIGN KEY(PID) REFERENCES PRODUCTS;

03/7/2021

HOW TO INSERT ROWS IN TABLES

SYNTAX1
INSERT INTO TABLENAME(COLNAME1,COLNAME2,......,COLNAMEN)
VALUES(VALUE1, VALUE2,..........,VALUEN);

COLNAMES ARE THE NAME OF COLUMNS SPECIFIED IN THE TABLE


VALUES OF COLUMNS HAS TO BE SEPERATED BY COMMA AND IF ANY VALUE IS
DATE OR CHARARRAY THEN SUCH VALUES NEEDS TO BE STORED IN SINGLE
QUOTES.

SYNTAX2
INSERT INTO TABLENAME(COLNAME1,COLNAME2,......,COLNAMEN)
VALUES(&COLNAME1, &COLNAME2,.........,&COLNAMEN);
HERE & IS AN INPUT OPEARTOR WHICH ASKS USER TO ENTER VALUES ON RUN
TIME
EXAMPLE.
INSERT INTO DEPARTMENT(DEPTID, DNAME, DEPTBGT,DEPTLOC)
VALUES(1001,'PROJECT',150000,'MUMBAI');
COMMIT;

INSERT INTO DEPARTMENT(DEPTID, DNAME, DEPTBGT,DEPTLOC)


VALUES(&DEPTID, &DNAME, &DEPTBGT,&DEPTLOC);

ENTER VALUE FOR DEPTID: 1002


ENTER VALUE FOR DNAME: QUALITY
ENTER VALUE FOR DEPTBGT: 200000
ENTER VALUE FOR DEPTLOC: THANE
COMMIT;

TO INSERT A NULL VALUE(MISSING VALUES)

INSERT INTO DEPARTMENT(DEPTID, DNAME, DEPTBGT,DEPTLOC)


VALUES(1003,'SALES',NULL ,'MUMBAI'); HERE DEPTBGT VALE WILL BE NULL

HOW TO UPDATE VALUES (AFTER SOME DAYS DEPTBGT VALUE IS KNOWN)


UPDATE DEPARTMENT
SET DEPTBGT = 250000
WHERE DEPTBGT IS NULL;

TO MODIFY EXISTING VALUES


UPDATE DEPARTMENT
SET DEPTBGT = BEPTBGT+10000
WHERE DEPTID = 1001;

5/7/2021

HOW TO SELECT THE RECORDS


SELECT IS A QUERY USED TO VIEW THE RECORDS FROM TABLE
SYNTAX

SELECT COLUMN1, COLUMN2,...|*


FROM TABLENAMES
WHERE ROW SELECTION CONDITION
GROUP BY COLUMNS SPECIFIED IN SELECT CLAUSE
HAVING GROUP SEARCH CONDITION
ORDER BY COLUMN ASC/DESC;
SELECT IS KEYWORD USED TO IDENTIFY EITHER *(ALL COLUMNS) OR COLUMNS
SPECIFIED IN TABLE

FROM IS KEYWORD USED TO SPECIFY THE TABLE NAMES CONTAINING


COLUMNS IN SELECT

WHERE IS KEYWORD USED TO SPECIFY CONDITIONS ON THE BASIS OF WHICH


DIFFERENT ROWS WILL BE SELECTED AND IT IS OPTIONAL

GROUP BY IS KEYWORD AND IS OPTIONAL USED TO GROUP THE ROWS ON THE


BASIS OF VALUES OF COLUMNS SPECIFIED IN SELECT CLAUSE

HAVING IS KEYWORD AND IS OPTIONAL USED TO SPECIFY RESTRICTION


(CONDITION) ON THE GROUPS AND WILL BE USED ALONG WITH GROUP BY

ORDER BY KEYWORD AND IS OPTIONAL USED TO SORT THE ROWS IN EITHER


ASCENDING ORDESCENDING ORDER ON BASIS OF SOME COLUMN IN SELECT
CLAUSE. ASC/DESC MEANS ASCENDING ORDER OR DESCENDING ORDER AND IF
NEITHER ASC NOR DESC IS SPECIFIED THEN DEFAULT IS ASC

05/7/2021
QUERIES
CONSIDER FOLLOWING TABLES
PRODUTS
MFRID PRID NAME PRICE QTYAV

ORDERS
ORDID DATE CUST REP MFRID PRID AMT QTY

CUSTOMER
CUSTID NAME REP CITY CREDITLIMIT REGION

SALESREPS
EMPID NAME JOINDATE REPOFF MGR SALES TARGET dob

OFFICE
OFFID MANAGER CITY REGION SALES TARGET

In above tables Office and Salesreps has cyclic dependency as both tables are having foreign key
which is primary key in either of the table
Along with this Salesreps table also has a foreign key mgr which is primary key empid in same
table which is called self related table

7/7/2021
Tables Office &Salesreps are having cyclic dependency as Office table is using a foreign key
from Salesreps table and Salesreps table is using a foreign key from Office table.

q.1 List all office’s details


q.2 List employees with their name id and sales.
q.3 List orders details
q.4 List orders accepted in last quarter of 2015
q.5 List products details with quantity available for more than 25
Ans. 1 Select *
From Office;
2 Select empid, name, sales
From salesreps;
3 Select *
From Orders;
4. Select ordid, date, qty, amt
From orders
Where date>=’01-OCT-2015’
And date<=31-DEC-2015’;
5. Select *
From Products
Where qtyav>25;

8/07/2021
q.6 List employees with their name sales and target for employees joining in first half of year
2018 and has sales more 50% of target.

q.7 List employees with their name sales and the amount by which sales is less than target for
employees joining in first half of year 2018 and has sales below target.

q.8 List orders accepted in 2nd half of 2019 and has been placed by customer with customer id
1001 and order amount is more 25000 sorted in ascending order of amount
Also write the query for above question by performing sorting in descending order
Ans
6 select name, sales, target
From salesreps
Where joindate>= ‘01-jan-2018’ (OR joindate between ’01-jan-2018’ and’30-06-218’)
And joindate<= ’30-06-2018’
And sales>target*0.5 (or target*50/100)
7 select name, sales, (target-sales)
From salesreps
Where joindate between ’01-jan-2018’ and ’30-jun-2018’
And sales < target;
08/07/2021
8 select ordid, date, qty, amt, mfrid, prid
From orders
Where date between ’01-jul-2019’ and ’31-dec-2019’
And cust = 1001
And amt > 25000
Order by amt asc;(If asc is not written then to default will be asc)
9 select ordid, date, qty, amt, mfrid, prid
From orders
Where date between ’01-jul-2019’ and ’31-dec-2019’
And cust = 1001
And amt > 25000
Order by amt desc(for descending order desc is mandatory)

q.10 List employees with their sales and target if sales less than 50% of target and have joined
in the last month of 2015

select empid, name, sales, target


from salesreps
where sales<0.5*target
and joindate between ’01-dec-2015’ and ’31-dec-2015’
(joindate>=’01-dec-2015’ and joindate<=’31-dec-2015’
Or
Extract month from joindate = ‘dec’

q.11 List products with quantity on hand if price is more rs.100 sorted in reverse of
alphabetical order of product name.
q.12 List customers with their name city and region if customer is residing in city Mumbai or
Thane sorted in alphabetical order of city name.

14/07/2020
11. Select mfrid, prid, name, price, qtyav
From products
Where price>100
Order by name desc;
When asc or desc is taken for numeric values then sorting is done accordingly but for non-
numeric values such as strings then asc means alphabetical order and desc means reverse of
alphabetical order.

12. select custid, name, city, region


From customer
Where city = ‘Mumbai’
Or city = ‘Thane’
Order by city;

Aggregate functions Functions which calculates aggregated values for different columns and
rows are aggregate functions, they are as follows
avg(), sum(), min(), max(), count()
Avg() calculates average value for specified numeric columns
Min() finds out the minimum value of specified numeric columns
Max() finds out the maximum value of specified numeric columns
Sum() add all the values of specified numeric column
Count() counts the total no of values of specified column or the row and the values can be
numeric or non-numeric, it has 2 syntaxes
1 count(columnname) counts the no of values of specified column
2 count(*) counts the no of rows

q.12 List minimum and maximum values of sales for employees


q.13 List average of order amount for all orders
q.14 List minimum and maximum of sales for employees who joined in 1st quarter of 2010
15/7/2021
Ans
12. Select min(sales), max(sales)
From Salesreps;
OP min(sales) max(sales)
50000 1000000 (eg.)

13. Select avg(amt)


From Orders;

14. Select min(sales), max(sales)


From salesreps
Where joindate between ‘01-jan-2010’ and ’31-mar-2010’;
Alternate ways of writing above condition
1. joindate>= ‘01-jan-2010’ and joindate<= ’31-mar-2010’
2. Extract month from joindate =’JAN’ or Extract month from joindate =’FEB’ or Extract
month from joindate =’MAR’

q.15 List average amount of orders accepted in 2 nd half of year 2018 and order is for a product
with mfrid as 1001 and product id as 2001.
q.16 List total no of orders accepted in the 2019.
q.17 List total no of employees joined in year 2017 or 2016.
q.18 List total no of sales values and total employees.

Ans
15 Select avg(amt)
From orders
Where date between ’01-jul-2018’ and ’31-dec-2018’
And mfrid = 1001
And prid = 2001;

16. Select count(*)


From orders
Where date between ’01-jan-2019’ and ’31-dec-2019’;
(OR extract( year from date) = 2019)

17. Select count(*)


From salesreps
Where joindate between ’01-jan-2016’ and ’31-dec-2017’;
(Alt cond. Extract (year from joindate) = 2016 or extract(year from
joindate = 2017)
16/07/2021
18. select count(sales), count(*)/count(empid) (sales having null values will not be counted)
From salesreps;
q.19 List employees with their name, sales, target and joindate grouped according their date of
join.
q.20 List product details grouped according to their quantity available
q.21 List orders with orderid date amount grouped according to their order date.

Ans19 select name, sales, target, joindate


From salesreps
Group by joindate, name, sales, target;
20 Select *
From products
Group by qtyav,mfrid,prid,name,price;
21 Select ordid, date, amt
From orders
Group by date,ordid,amt;
q.22 List customers with their id name city region and creditlimit if customer has a creditlimit
of 50000 or above and the city is in eastern region grouped according to their city.

22 select Custid, name, city, region, creditlimit


From customers
where creditlimit>=50000
And region = ‘eastern’
Group by city, custid, name, region, creditlimit;
31/7/2020
Pattern Matching Test
Pattern matching test is used to search records from table when the exact pattern of string is not
known. In pattern matching test we specify the characters that we know along with wild card
characters, where wild card character replaces the unknown characters in the string. If a single
character is not known then underscore(_) is used and if multiple characters are not known then
we can use % or $. When a pattern matching is used it has to be combined with keyword like in
where clause and its syntax in where clause is as follow
Select…..
From …..
Where column_name like ‘%abc_’
In the above syntax % will search for any number of characters before abc and exactly one
character after abc, this can be useful when we are searching for records when the strings are not
known completely.

Q.23 List employees with their name sales target and date of join for employees whose name
starts with a character A.
Q.24 List employees with their name sales target and date of join for employees whose name
starts with 2nd character as A and ends with last character as n.
Q.25 List Customers with their name id and creditlimit if name starts with 3 rd character as c
and ends with 2nd last character as o

Ans 23 Select name, sales, target, joindate


From salesreps
Where name like ‘A%’;
24 Select name, sales, target, joindate
From salesreps
Where name like ‘_A%n’
25 select custid, name, creditlimit
From customers
Where name like ‘__c%o_’;
17/07/2021
Q.26 List employees with their name sales target and joindate if employee’s name is starting
with 3rd character as d and ending with 3rd last character as j and is above performance by 10%
and has joined in month of January or April or October.

Ans 26 Select name, sales, target, joindate


From salesreps
Where name like ‘__d%j__’
And extract (month from joindate) = ‘jan’
Or extract (month from joindate)= ‘apr’
Or extract (month from joindate) = ‘oct’
And sales>target*1.1; //target*110/100

Escaping wild card characters


Suppose the patterns that we are searching contains wild card characters in the string and when
we use like then even those wild card characters will act as multiple or single character match so
we need to omit such characters by using escape along with like.
Eg. Suppose table contain names having wild card characters such as $ and we want to perform
queries using like.
Q.27 List employees with their name joindate sales and target if name starts with 2 nd characters
as r and has 3rd character as $ and last character as g.
Ans 27 Select name, joindate, sales, target (above query without escaping)
From salesreps
Where name like ‘_r$%g’;
The above query will give all names having any character at 1st place then r as 2nd character and g
as last with any no of characters in between but we want $ as a character in the output so the
above query will change as follows.
Select name, joindate, sales, target
From salesreps
Where name like ‘_r*$%g’ escape ‘*’;
The wild card character that is to be omitted will be preceded by one more wild card character
and escape will use that additional wild card character added.

22/7/2021
Q.28 List employees with their name date of join age and the sales amount by which it is above
or below the target for employees with dob before 1990 and name has 2 nd character as b 2nd last
character as h and last character as *.

Ans. Select name, joindate, (sysdate – dob) as age, (target – sales) as amount
From salesreps
Where dob<’01-01-1990’
And name like ‘_b%h$*’ escape ‘$’;

Q.29 List Offices with sales and target and city if it falls in eastern region and has target more
than sales at least by 5000 and city is starting with a character D.

Ans Select offid, sales, target, city


From office
Where (target-sales)>=5000
And city like ‘D%’
And region = ‘eastern’;

22/7/2021

Q.30 List employees with their name sales target if diff of target to sales is more the 10000
having name with 1st character as a.

Ans Select sales, target, name


From salesreps
Where (target – Sales)>10000
And name like ‘a%’;
Q.31 List all employees with their name, sales, target, joindate, age and no of years for which
they have worked if their age is more than 50 yrs and have worked for at least 20 yrs and name
has a character a and target is more than sales by 20000

Ans Select name, sales, target, joindate, (sysdate – dob), (sysdate – joindate)
From salesreps
Where (sysdate – dob) > 50
And (sysdate – joindate)>=20
And name like ‘%a%’
And (target – sales) > 20000;

Multi – Table Queries (Joins)


Multi table queries are also referred as join query which is a query written using 2 or
more no of tables, where for writing such queries tables will use the relationships of foreign key
and primary key through which tables are connected.

Joins are of basically 2 types which are


I Equi – join (Joins written using = operator)
II Non – equi – join (Joins written using non equality operator and not having any
further type)
Further equi – join can be either
I Natural join or inner join: It’s a join using the pk and fk relnship
II Only Equi join: It’s a join using columns of same data type but not pk & fk
III Outer Joins which is again of 3 types
I Left outer join
II Right outer join
III Full outer join

A join performed without using any of above type, where only table names are specified in from
clause and it is known as Cartesian product or Cross join. For any of above types of joins
database performs Cartesian product of table and then applies conditions specified in where
clause.

Cartesian product(Cross join) it is defined as table multiplication i.e. tables specified in from
clause are simply multiplied which means if 1 st table consist of 20 rows and 2 nd table consist of
25 rows then cross join will consist of 500(20*25) rows.
Consider an example for cross join with 2 tables customer and salesreps as follows with some
sample rows
Customer
CUSTID NAME REP CITY CREDITLIMIT REGION
101 - - Mumbai - -
102 - - Mumbai - -
103 - - Thane - -
104 - - Mumbai - -
105 - - Thane - -

Salesreps
EMPID NAME JOINDATE REPOFF MGR SALES TARGET dob
201 - - 1001 - - - -
202 - - 1001 - - - -
203 - - 1002 - - - -

Now Cartesian product query is written as follows

Select Customer.name, Salesreps.name


From Customer, Salesreps;

Cartesian product of above tables is denoted as follows


Customer × Salesreps its product is as follows
CUSTID NAME REP CITY CREDITLIMIT REGION EMPID NAME JOINDATE REPOFF MGR SALES TARGET DOB
101 - - Mumbai - - 201 - - 1001 - - -
-
101 - - Mumbai - - 202 - - 1001 - - - -
101 - - Mumbai - - 203 - - 1002 - - - -
102 - - Mumbai - - 201 - - 1001 - - -
-
102 - - Mumbai - - 202 - - 1001 - - - -
102 - - Mumbai - - 203 - - 1002 - - - -
.
.
.

Total no rows will be 15

Natural join (Inner join) An equi join performed using parent and child relnship between the
tables is known as natural join or inner join, such a join is called natural or inner because tables
are inherently connected with fk & pk
Syntax Select ---------------
From table1, table2,…..
Where fk = pk
And similarly more conditions can be given depending upon no of tables in from
clause.

Eg. Select empid, name, ordid, amt


From salesreps, orders
Where rep = empid;
In the above query if we remove where clause then it will become a Cartesian product which for
writing queries using joins always there will Cartesian product. After Cartesian product the query
applies with other conditions.

q.32 List orders with id date amount along with name of the product and price.

Ans Select ordid, date, amt, price, name


From orders, products
Where orders.mfrid = products.mfrid
And orders.prid = products.prid;
q.33 List employees with their id, name and target along with customer with id name and
credit limit if credit limit is more than 50000 and customer is assigned to an employee with name
starting with first character as D and ending with j.
Ans Select empid, salesreps.name, target, custid, customer.name, creditlimit
From salesreps, customer
Where rep =empid
And creditlimit > 50000
And salesreps.name like ‘D%j’;

q.34 List orders with id date amount along with products with name and price if inventory
value of product is more that 100000 and order has been accepted by an employee with sales
more than target and employee is working in office with sales below target.
Ans select ordid, date, amt, products.name, price
From orders, products, salesreps, office
Where orders.mfrid = products.mfrid will join orders with products table
And orders.prid = products.prid
And rep = empid//will join orders with salesreps table
And repoff = offid //will join salesreps with office table
And price * qtyav > 100000
And salesreps.sales > salesreps.target
And office.sales<office.target;
q.35 List orders with id date amount and ordered quantity if order is placed for a product with
inventory more than 500000 and order is placed by a customer residing in eastern region and is
assigned to an employee with sales less than 50% of target sorted in descending order of amount.

Ans Select ordid, date, amt, qty


From orders, products, customer, salesrpes
Where orders,mfrid =products.mfrid
And orders.prid = products.prid
And orders.rep = empid
And cust =custid
And customer.rep = empid
And Price*qtyav > 500000
And region = ‘eastern’
And sales<0.5*target
Order by amt desc;
Q35a. List employees with their id name sales target along with their assigned customers with
name and credit limit if credit limit is above 50000 and customer resided in western region and is
having name starting with 1st character as A and ending with 3rd last character as c sorted in
ascending order of sales.
Select empid, salesreps.name, sales, target, customer.name, crditlimit
From customer, salesreps
Where rep = empid //will join customer & salesreps table
And creditlimit>50000
And region = ‘western’
And customer.name like ‘A%c__’
order by sales asc;
Q35b. List products with id, name and inventory value along with orders with id, date and amt
for those products if order is placed in last quarter of 2020 and it is placed by a customer with
credit limit above 50000 residing in eastern region.
Select products.mfrid, products.prid, products.name, qtyav*price as inventory, ordid,
date, amt
From products, orders, customer
Where orders.mfrid = products.mfrid
And orders.prid = products.prid
And cust = custid
And date between ’01-oct-2020’ and ’31-dec-2020’
And creditlimit>50000
And region = ‘eastern’;
Q35c. List office with sales and target in western region having an employee with more than 200
percent performance.
Select offid, office.sales, office.target, region
From office, salesreps
Where repoff = offid
And sales > target *2
And region = ‘western’;
Q35d. List office with sales and target in western region if office is managed by an employee
with more than 150 percent performance.
Select offid, office.sales, office.target, region
From office, salesreps
Where manager = empid
And sales > target *1.5
And region = ‘western’;
Self Join a natural join where a table joins with itself if known as self join. For a self join
query we have to alias the table with 2 different names so that we can visualize the same table as
two different tables.
Syntax
Select t1.column,…,t2.column,…..
From table t1, table t2
Where t1.fk = t2.pk;

q.36 List employee names along with their manager names.


Sample values in salesreps table
Salesreps
EMPID NAME JOINDATE REPOFF MGR SALES TARGET dob
101 Ramesh - - NULL - - -
102 Suresh - - 101 - - -
103 Kamlesh - - 101 - - -
Op should be
e.Name m.Name
Suresh Ramesh
Kamlesh Ramesh

Select e.name, m.name


From salesreps e, salesreps m
Where e.mgr = m. empid;
Let us visualize the table salesreps with names e & m
E
EMPID NAME JOINDATE REPOFF MGR SALES TARGET dob
101 Ramesh - - NULL - - -
102 Suresh - - 101 - - -
103 Kamlesh - - 101 - - -
M
EMPID NAME JOINDATE REPOFF MGR SALES TARGET dob
101 Ramesh - - NULL - - -
102 Suresh - - 101 - - -
103 Kamlesh - - 101 - - -

q.37 List employee id and name along with their manager id & name

Select e.empid, e.name, m.empid, m.name


From Salesreps e, salesreps m
Where e.mgr = m.empid;
e.empid e.Name m.empid m.Name
102 Suresh 101 Ramesh
103 Kamlesh 101 Ramesh

Q.38 List employee with their id name sales and target along with their manager’s id name
sales & target if employee’s performance is more than 150% and employee has joined in last
quarter of 2017.
Select e.empid, e.name, e.sales, e.target, m.empid, m.name, m.sales, m.target
From salesreps e, salesreps m
Where e.mgr = m.empid
And e.sales > (e.target * 1.5)
And e.joindate between ‘1-oct-2017’ and ’31-dec-2017’;

Outer joins
Outer joins are queries used to get additional rows from the tables specified in natural
join (inner join). The rows that are returned by outer joins are the rows of inner join along with
any rows in the table that are not mapped with primary key and foreign key relnship.
Outer joins are of 3 types
Left outer join
Right outer join
Full outer join
Left outer join This join will return additional rows that are not mapped from LHS table along
with op of inner join, its syntax is
Select col1, col2, …….
From Table1, Table2
Where fk (+)= pk plus inside the bracket on the left hand side of equal to is left outer
join
Right outer join This join will return additional rows that are not mapped from RHS table along
with op of inner join its syntax is
Select col1, col2, …….
From Table1, Table2
Where fk =(+) pk plus inside the bracket on the right hand side of equal to is right outer
join

Full outer join This join will return additional rows that are not mapped from LHS table and
RHS table along with op of inner join, its syntax is
Select col1, col2, …….
From Table1, Table2
Where fk (+)=(+) pk plus inside the bracket on the left hand side and right hand side of
equal to is full outer join.

q.39 List Employees with their id name sales target along with the orders that they have
accepted and the employees who have not accepted any order.
Select ordid, date, amt, empid, name, sales, target
From orders, salesreps
Where rep = (+)empid Right outer join
Sample op
ordid date amt Empid name sales target
1001 - 1000 101 Ramesh 10000 25000
1002 - 1500 102 Suresh 5000 30000
NULL NULL NULL 103 Rajesh 0 40000

q.40 List employees who have not been assigned to any customer;
Select empid,salesreps.name, custid, customer.name
From salesreps, cutomer
Where empid(+) = rep; Left outer join
Sample op
Empid saleresp.name custid, customer.name
101 Ramesh 201 Aditya
102 Suresh NULL NULL
Q.41 List employees along with their customer and any employee not assigned a customer and
any customer not assigned an employee.
Select empid,salesreps.name, custid, customer.name
From salesreps, customer
Where empid(+) = (+)rep; full outer join
Sample op
Empid saleresp.name custid, customer.name
101 Ramesh 201 Aditya
102 Suresh NULL NULL
NULL NULL 202 Abhik
Equi- join without Pk & Fk A join written without pk & fk relationship is called equi-join. The
columns that are used for joining must have same data type.
q.42 List employee if employee have accepted an order on the date of join
Select empid, name
From salesreps, orders
Where joindate = date;
q.42a List customer along with employee if any having credit limit same as sales of employee.
Select custid, customer.name, empid, salesreps.name
From customer, salesreps
Where customer.creditlimit = salesreps.sales;
q.43 List employee names along with their order amounts sorted in reverse of alphabetical
order of name.
Select name, amt
From salesreps, orders
Where rep = empid
Order by name desc;
Group by clause is a clause used to group the selected records on the basis of columns specified
in select clause. All columns except aggregate functions specified in select must be used in group
by.
For example if we want the orders to be placed in groups of employees ie orders to be
grouped employee wise then group by clause can be used.
Having clause is a clause used to perform search within the groups or if we want to specify
condition on the groups. When a query is using having clause then it should also use group by
where as a group by can be used without having
For example if we want to list employees to be listed with total no of orders with
minimum some no of orders then group with having is mandatory.

q.44 List employees with their order details grouped according to employee.
Select empid, name, ordid, orddate
From salesreps, orders
Where rep = empid
Group by empid, name, ordid, orddate;
The above query will list empid, name, ordid and orddate grouped according to empid and then
within empid records will be grouped according to name and then grouped according to ordid
and then according to orddate.
q.45 List employees with their name and total no of orders.
Select name, count(*)/count(ordid)
From salesreps, orders
Where rep = ordid
Group by name;
q.46 List employees with their name and total no of orders more than 5.

Select name, count(*)/count(ordid)


From salesreps, orders
Where rep = empid
Group by name
Having count(ordid) > 5;
q.47 List office details with minimum 5 employees.
Select offid, city, region, manager, count(*)
From office, salesreps
Where repoff = offid
Group by offid, city, region, manager
Having count(*)>=5;
Note: Writing fk = pk or pk = fk in joins has no impact on output but if pk = fk has been written
then it will impact the speed of the query i.e it will be slowed down.
q.48 List products with inventory values if inventory values are more than 100000 and product
has orders more than 500000;
select p.mfrid, p.prid, name, price*qtyav
from products p, orders o
where o.mfrid = p.mfrid
and o.prid = p.prid
and price*qtyav > 100000
group by p.mfrid, p.prid, name, price*qtyav
having sum(amt) > 500000;
11/8
q.49 List customer details with their employee name if customer has placed a minimum of
total no of orders 10
select custid, c.name, c.rep, city, s.name
from cusctomer c, salesrep s, orders o
where c.rep = empid
and o.rep = empid /cust = custid
group by custid, c.name, c.rep, city, s.name
having count(*) >= 10;
q.50 List employees with their orders for products with product name starting with 1 st
character as A and ending with second last character as e and order has been accepted in last
quarter of 2018 such that there are minimum 10 orders.
Select empid, s.name ,date , ordid,date
From salesreps s, products p, orders o
Where o.mfrid = p.mfrid
And o.prid = p.prid
And rep = empid
And p.name like ‘A%e_’
Orddate between ’01-oct-2018’ and ’31-dec-2018’
Group by empid, s.name ,ordid,name
Having count(*)>= 10;
Q.51 List office details with employees working under those offices if employees have
accepted a minimum of 20 orders and total amount of 100000.
Select empid, name, offid, city, region
From office, salesrep, order
Where repoff = offid
And rep = empid
Group by empid, name, offid, city, region
Having count(*) >= 20
And sum(amt) = 100000;

Q.52 List customers with total no of employees assigned if customer has placed an average
order amount of more than 5000;
Select custid, c.name, c.rep, city, region, count(*)
From customer c, salesreps, order
Where c.rep = empid
And cust = custid
Group by custid, c.name, c.rep, city, region
Having avg(amt) > 5000;
Q.53 List products with inventory values if product name starts with 2nd character as b and ends
with 3rd last character as c and has an average order amount of at least 10000 and order has been
accepted by an employee joined in 1st half of 2015.
Select p.mfrid, p.prid, p.name, price*qtyav
From products p, orders o, salesreps s
Where o.mfrid = p.mfrid
And o.prid = p.prid
And rep = empid
And p.name like ‘_b%c__’
And joindate between ‘1-jan-2015’ and ‘3-jun-2015’
Group by p.mfrid, p.prid, p.name, price*qtyav
Having avg(amt) >=10000;
Sub – Query Sub query is defined as a query within another query or it is also defined as a
query inside another query.
Syntax Select --------
From -------
Where columnname/without columnname operator (Select-------
From-----
Where--- )
A sub query can be written in either where clause or having clause. If sub query condition is
based on individual rows then sub query is to be written in where clause and if condition is based
on aggregate functions ( count, sum, min, max, avg) then sub query is to be written in having
clause. The operator between the two queries can be relational op(=, >, >=, <, <=, !=) or set
membership operator (in/not in) or existential operator(exists/not exists) or Quantifier operator
(Any/All) depending upon the type of sub query. We have following types of sub queries.
i. Sub query with comparison test
ii. Sub query with Quantified test
iii. Sub query with existence test
iv. Sub query with set member ship test
Sub query with comparison test A sub query with comparison test can be written in either
where or having clause depending upon the type of condition, its syntax is as follows
Select --------
From -------
Where columnname reln operator (Select -- // inner query must return only one row as op
From-----
Where--- )
Also sub query has outer query and inner query

Q.54 List employees with their id and name having sales less than average sales of all
employees.
Select empid, name
From salesreps
Where sales < avg(sales) (aggregate functions are not allowed in rhs of condition and
it is incorrect and correct query is as follows)
Select empid, name
From salesreps
Where sales < ( Select avg(sales)
From salesreps);
Note: Always inner query runs first then the output returned by inner query will be used to
execute the outer query.
Q.55 List orders detail if order amount is less than average order amount.
Select ordid, date, amt
From orders
Where amt < (select avg(amt)
From orders);
Q.56 List employees if there sales is less than average customer credit limit
Select empid, name, sales
From salesreps
Where sales < (select avg(crdtlmt)
From customers);
Q.57 List employees if their sale is less than their total order amount.
Select empid, name, sales
From salesreps
Where sales < ( select sum(amt)
From orders
Where rep = empid);
The inner query is using a condition rep = empid, where empid is a column in table of outer
query, such a query is said to have an outer reference as inner query is referring a table in outer
query.
A sub query having outer reference is known as co – related sub query.

Sub query with quantified test A sub query using any/all in condition along with column name
is known as sub query with quantified test and syntax is as follows
Select ----
From
Where columnname relnop any/all ( select -----
From---
------
);
Q.58 List employees with their sales if their sales is less than target of all employees.
Select empid, name, sales
From salesreps
Where sales < all ( select target
From salesreps)
Replacing all with any and vice versa

Select empid, name, sales


From salesreps
Where sales > any ( select target
From salesreps)
Q.59 List order details if order amount is more than sales of an employee.
Select ordid, date, amt
From orders
Where amt > any (select sales
From salesrpes);
Note: In this type of sub query inner query can return multiple rows as output.
Sub query with set membership operator This type of sub query uses a set membership
operator (in/not in) instead of reln operator along with column name in where clause. Inner query
returns multiple rows as output and then it is verified with set operator to execute outer query
and its syntax is
Select -----
From ------
Where columnname in/not in ( select -----
From---
-------);
Q.60 List employee detail if they accepted any order of amount for more than 500.
Select empid, name, joindate, sales
From salesreps
Where empid in (select rep
From orders
Where amt > 500);
This query can very well be written using joins
Select empid, name, joindate, sales
From salesreps, orders
Where rep = empid
And amt > 500;
Note: All queries that can be written with joins can equally be written with sub query with set
member ship test and vice versa. Writing query with joins does Cartesian product which is table
multiplication which means no of rows will increase multiplicatively which is also known as
exponential growth, where if sub query is written instead of joins then no of rows will grow
additively which means no of rows will be added from both tables so there will be huge
difference in no of rows in both approaches and hence huge difference between no of times the
query will run in both approaches and hence we prefer using sub queries instead of joins when
table grows.

Sub query with existence test In this type of sub query there is no column specified in where
clause, it will directly have exists/not exists in where clause followed by sub query and its syntax
is given as follows
Select ----------
From ----
Where exists/ not exists ( select *
From --------
Where inner table.fk/pk = outer table.fk/pk)
From syntax it is clear that inner query is using a column from outer query which is called outer
reference. Evaluation of such a query is based on whether inner query returns any row or not and
hence we simply write select *. If inner query returns any row then it is interpreted as true
otherwise false, which means if true is returned then outer query will run otherwise outer query
will not run.
Q.61 List the offices where there is a salesperson whose target represents more than 55
percent of the office’s target.
Select offid, region, city
From offices
Where exists (select *
From Salesreps
Where repoff = offid
And target > (0.55*offices.target));
Above query with not exists
Select offid, region, city
From offices
Where not exists (select *
From Salesreps
Where repoff = offid
And target < (0.55*offices.target));

q.62 List the products for which an order of $25,000 or more has been received ( use exist).
Select mfrid, prid, name
From products
Where exists ( select *
From orders
Where mfrid = products.mfrid
And prid = products.prid
And amt >=25000);
With not exists
Select mfrid, prid, name
From products
Where not exists ( select *
From orders
Where mfrid = products.mfrid
And prid = products.prid
And amt <= 25000);
View It is defined as a virtual table, which means it can be visualized as a table but it is not
physically created table. Since it can be visualized as a table, so all the operations that can be
performed in tables can equally be performed in views also.

Uses of view It can be used to (advantages of a view)


1> Simplify the complex queries into simple query by breaking down the complex
queries into simple and multiple queries so that queries can be executed into parts.
If complex queries are not broken down into parts then they are going to be difficult
to write and very lengthy to execute by the system.
2> To implement security in the system as if records are accessed through a view then
actual tables are hidden from the user and adding security in the table.
Disadvantage of a view Since there is no physical table created so the query to create view
remains in main memory(RAM) and when ever needed, it executes and it is also called as a
dynamic feature of database as it will run when ever needed, so extensive use of view will slow
down the database performance.
Syntax Create view viewname as
Select --------/*
From tablenames separated by comma
Where condns;
Types of views There basically 2 types of views
1> Horizontal view
2> Vertical view
Horizontal view It is a view created from exactly one table by writing a query with select * only
along with other clauses as may be needed. When a horizontal view is created then all updates
performed in view will also update the actual table and hence it can be used for adding
security.
Eg. Create a view called bigorders for the orders with amount more than 50000
Create view bigorders as
Select *
From orders
Where amt > 50000;
o/p View created.
Now the view created can be used for various purposes such as selection, insertion, deletion
and update all records affected in view will also affect the table orders.
Eg update bigorders
Set amt = amt+amt*0.1;
So above update will increase the order amount by 10% and will also affect the table orders and
amounts will increased by 10% for all orders having amount more than 50000

Vertical view It is a view created by writing the queries with specific column names in the select
clause from one table or more than one table. Since this type of view can be from multiple
tables and hence it can use joins sub queries etc.
Eg. create a view of employees with their id, name, sales, target, order id order date and
amount for employees with sales less than 50% of target

Create view EMPORDER as


Select empid, name, sales, target, ordid, date, amt
From salesreps, orders
Where rep = empid
And sales < 0.5*target;
o/p view created
Note that in vertical view if we perform any update then it will not affect the actual table.
Vertical view can be of different types such as joined view, grouped view and materialized view
depending type of query used for creating view such the above view is a joined view as there is
use of a join query. A materialized view is a view with a complex query where complexity of a
query will be determined by the system itself it is called materialized as for such views database
creates a temporary table for the time the view is under use.

Relational Algebra As part of System R project given by Dr. Codd in 1972, it consist of different
things such as relational algebra, relational calculus, ER Modeling and Relational model. On the
basis of relational algebra, very popular language SQL has been built and on the basis of
relational calculus other languages such as PROLOG, LISP and R programming has been
developed.
Relational algebra is a procedural (language) approach towards programming, which is a
mathematical background for development of SQL and hence SQL and PL/SQL is also procedural
programming language.
Relational algebra consist of different mathematical operators using which different
types expressions can be written which later got converted into SQL queries. Different
operators in Relational algebra are as follows
1> Projection
2> Selection
3> Cartesian product ( Cross product)
4> Joins( Natural join, Left, Right & Full)
5> Rename
6> Assignment
7> Set difference
8> Union
9> Intersection
Unary & Binary op An operator which takes only one operand is called unary operator and
operator taking 2 operands is called binary operator eg. =, +, -, * etc are binary – is unary also as
some times it is used with one operand only eg -6, ^(not or negation), in C prog ++, - - even they
are unary.
1> Projection Projection is a unary operator and it is denoted as π and read as pi. It
operates over operand by taking vertical cross section of the relation( table) ie it does
the selection of columns from specified relation, its syntax is given as follows
Π c 1 ,c 2 ,c 3 … (r), where pi is operator and c1, c2… are the columns and r is relation
form where the columns will be extracted.
for eg. Π empid, name, joindate( salesreps), this expression will extract the columns
empid, name and joindate from the relation salesreps, it is equivalent to a query in SQL
given as follows
select empid, name, joindate
from salesreps;
2> Selection Selection is also a unary operator and it is denoted as σ read as sigma. It
operates over operand by taking horizontal cross section of the relation( table) ie it does
the selection of tuples(rows) from specified relation, its syntax is given as follows
σ p(r), where σ is operator, p is predicate which means it is the condition specified
for selection of rows and r is relation from where the rows will be selected.
For eg. σ sales>10000(salesreps), this expression will select all tuples with sales more than
10000 from the relation salesreps, it is equivalent to a query in SQL as follows
Select *
From salesreps
Where sales > 10000;
Combination of Selection & Projection both operators can be used together to perform
different types of extraction from the tables(relation), the syntax of combination is given as
follows
Π c 1 ,c 2 ,c 3 ,… …(σ p 1, p 2 ,… . (r))

For eg. Write an expression to list employees with their id, name and join date if sales more than
10000 and target more than 50000.
Π empid , name , joindate(σ sales>10000 >50000 (salesreps))
target

Equivalent query in SQL is


Select empid, name, joindate
From salesreps
Where sales > 10000
And target > 50000;

Cartesian Product It is denoted as × and read as cross and it is defined as table multiplication
where each tuple in first relation will multiply with every tuple in 2 nd relation. It is a binary
Operator. If r1 & r2 are two relations then its syntax is given as follows
r1 × r2
for eg. Consider Cartesian product with 2 tables customer and salesreps as follows with some
sample rows
Customer
CUSTID NAME REP CITY CREDITLIMIT REGION
101 - 201 Mumbai - -
102 - 201 Mumbai - -
103 - 202 Thane - -
104 - 202 Mumbai - -
105 - 203 Thane - -

Salesreps
EMPID NAME JOINDATE REPOFF MGR SALES TARGET dob
201 - - 1001 - - - -
202 - - 1001 - - - -
203 - - 1002 - - - -

Now Cartesian product query is written as follows

Customer × Salesreps
Cartesian product of above tables is given as follows

CUSTID NAME REP CITY CREDITLIMIT REGION EMPID NAME JOINDATE REPOFF MGR SALES TARGET DOB
101 - - Mumbai - - 201 - - 1001 - - -
-
101 - - Mumbai - - 202 - - 1001 - - - -
101 - - Mumbai - - 203 - - 1002 - - - -
102 - - Mumbai - - 201 - - 1001 - - -
-
102 - - Mumbai - - 202 - - 1001 - - - -
102 - - Mumbai - - 203 - - 1002 - - - -
Total there will be 15 rows

Natural Join It is denoted as ⋈ and read as dumbbell and it is the extension of Cartesian product where
the selection condition of primary key and foreign key is applied over the Cartesian product. It is a binary
operator and its if r1 & r2 are two relation its syntax is given as follows
r1 ⋈ r2
For if customer and salesreps are two relations as follows
Customer
CUSTID NAME REP CITY CREDITLIMIT REGION
101 - 201 Mumbai - -
102 - 202 Mumbai - -
103 - 203 Thane - -
104 - 201 Mumbai - -
105 - 203 Thane - -
Salesreps
EMPID NAME JOINDATE REPOFF MGR SALES TARGET dob
201 - - 1001 - - - -
202 - - 1001 - - - -
203 - - 1002 - - - -
Then their natural join is denoted as follows
Customer ⋈ Salesreps its output is given as follows
CUSTID NAME REP CITY CREDITLIMIT REGION EMPID NAME JOINDATE REPOFF MGR SALES TARGET DOB
101 - 201 - - - - - - - - - -
102 - 202 - - - - - - - - - -
103 - 203 - - - - - - - - - -
104 - 201 - - - - - - - - - -
105 - 203 - - - - - - - - - -
Performing natural join using Cartesian product Natural join can also be performed by using
Cartesian product in combination with select operator and syntax is given as follows if r1 & r2
are the relations
σ p 1, p 2 ,… . (r1 × r2)
Also the above syntax can be combined with projection operator to extract columns from natural
join as follows
Π c 1 ,c 2 ,c 3 ,… …(σ p 1, p 2 ,… . (r1 × r2))

Eg .1 Write an expression to list employees with their id name order date and amount if sales is
more 10000.( Write using natural join and Cartesian product)
Π empid , name ,date , amt (σ sales >10000 ( salesreps ⋈ orders)) using natural join
Π empid , name ,date , amt (σ rep=empid >10000 (Salesreps × orders))
sales
An equivalent query in SQL is given as follows
Select empid, name, date, amt
From salesreps, orders
Where rep = empid
And sales > 10000;
Eg. Write an expression using natural and Cartesian product to find products with name quantity
available and amount of order if price is more than 100;
Π name , qtyav , price , amt (σ price>100( products ⋈ orders))
Π name , qtyav , price , amt (σ mfrid=mfrid = prid >100 (products × orders))
prid price

Using SQL
Select name, qtyav, price, amt
From products p, orders o
Where o.mfrid = p.mfrid
And o.prid = p.prid
And price > 100;

Outer Join Left & Right outer join It is denoted as ⟕ and ⟖ respectively and   for full outer
join read as dumbbell with extension and it is the extension of Cartesian product where the selection
condition of primary key and foreign key is applied over the Cartesian product. If we are using left outer join
then we will get additional tuples form left hand side table and if right outer join then additional tuples from
right hand side table and if full outer join additional tuples from left hand side table and right hand side table.
It is a binary operator and if r1 & r2 are two relation then its syntax is given as follows

r1 ⟕ r2 left outer join


r1 ⟖ r2 right outer join
r1 r2 full outer join
Consider an example taken above
Write an expression to list employees with their id name order date and amount if sales is more
10000. Also find employees who may not have accepted any order ( Write using natural join and
Cartesian product)
Using left outer join
Π empid , name ,date , amt (σ sales>10000 ( salesreps ⟕ orders))
Using SQL
Select empid, name, date, amt
From salesreps, orders
Where empid (+) = rep
And sales > 10000;
Using Right outer join
Π empid , name ,date , amt (σ sales>10000 ( orders ⟖ salesreps))
Using SQL
Select date, amt, empid, name
From orders, salesreps
Where rep = (+) empid
And sales > 10000;
If we want additional rows from left & right hand side both then Full outer join is as folows
Π empid , name ,date , amt (σ sales>10000( orders salesreps))
Using SQL
Select date, amt, empid, name
From orders, salesreps
Where rep (+) = (+) empid
And sales > 10000;

Rename It is denoted as ρ and it is read as rho. It is a unary operator and it does renaming of
specified relation with a new name specified within operator and its syntax is given as follows if
r1 is a relation and we want to rename it as s1
ρ s1 (r1) r1 will be renamed as s1
eg. ρ sales1 ( salesreps)

Assignment It is denoted as -> and it is a binary operator an it assigns a specified relation to


another relation. If r is a relation to be assigned t another relation r then its syntax is given as
follows
r->s r is assigned to s
eg salesreps -> sales
eg for assignment operator expression in SQL is creating a table using another
for eg
create tables sales as
( select * from salesreps
Where sales > 50000)
Above query will create a table sales by copying the rows from salesreps for employees with
sales > 50000.

Set Difference It is denoted as – and read as minus. It is a binary operator. If r & s are two
relations then its syntax is given as follows
r – s relation s will be subtracted from relation r
r & s must satisfy following rules to use –
i> r & s must be of same arity ie they must have same degree, which means no of
attributes in r & s must be same.
ii> Domain of ith attribute in r must be same to domain of ith attribute in s ie
corresponding attribute in both relations must be of same domain
Note: Domain is set of legal values for an attribute which means attributes must have same
data types and same range of values.
Degree is no of attributes in a relation
Eg if Salesreps and sales as two relations then expression can be written as
Salesreps – sales we will get all employees with sales below 50000 as sales
is defined previously with all employees with sales > 50000
In SQL set difference can be illustrated with sub queries with except keyword

Select *
From salesreps
Where except ( select * from
Salesreps
Where sales > 50000) we will get all employees with sales below
50000

Union It is denoted U and read as union. It is a binary operator. If r & s are two relations then its
syntax is given as follows
r U s It will combine the tuples of r with tuples of s by avoiding the duplicate tuples ie
if a tuple belongs to both relation then it will be listed once

For r & s to use union, they must satisfy following two conditions
i> r & s must be of same arity ie they must have same degree, which means no of
attributes in r & s must be same.
ii> Domain of ith attribute in r must be same to domain of ith attribute in s ie
corresponding attribute in both relations must be of same domain
Eg. Write an expression using union to find employee ids if either they have sales more than
50000 or have order amount more than 10000
Π empid (σ sales>50000(salesreps)) U Π rep(σ amt>10000 (orders))
IN SQL
Select empid
From salesreps
Where sales > 50000
Union
Select rep
From orders
Where amt > 10000;
Intersection It is denoted as Ո and read as intersection. It is a binary operator. If r & s are two
relations then its syntax is given as follows
r Ո s It will combine the common tuples of r & s by avoiding the duplicate tuples ie the
tuple which belongs to both relations will only be listed once

For r & s to use union, they must satisfy following two conditions
i> r & s must be of same arity ie they must have same degree, which means no of
attributes in r & s must be same.
ii> Domain of ith attribute in r must be same to domain of ith attribute in s ie
corresponding attribute in both relations must be of same domain.
Eg. Write an expression using intersection to find employee ids if either they have sales more
than 50000 and have order amount more than 10000
Π empid (σ sales>50000(salesreps)) Ո Π rep(σ amt>10000 (orders))
IN SQL
Select empid
From salesreps
Where sales > 50000
intersect
Select rep
From orders
Where amt > 10000;
Relational Calculus Relational calculus is a non-procedural language developed as part System
R Project. It is mathematical background behind development of scripting and AI based
languages. Languages such as R, Python, LISP, Scheme and PROLOG are based on the
approach of relational calculus.
Relational calculus is divided into two different types of languages namely tuple relational
calculus and domain relational calculus

Tuple relational calculus It is a sub-language of relational calculus which has been based on
tuple selection from specified relation and mathematically it is defined as
{t / p(t) } and it is read as set of tuples such that predicate p over t is true, where predicate
p is conditions over tuples.
Eg. Find all employees if there sales is more than 50000
{ t / t(salesreps) ^ t.sales > 50000 }

Domain Relational calculus It is a sub-language of relational calculus which has been


based on domain(column) selection from relations and mathematically it is defined as
{<d1, d2,…>/d1,d2,…∈R^p(d1)^p(d2)….} and is read as set of all domains from
relation R with predicates being true over the domains.
Eg. Find employee id name join date and sales if sales more than 50000 and date of join
is before 2018.
{<empid, name, joindate, sales>/empid, name, joindate, sales ∈ salesreps ^
sales>50000^joindate<’01-01-2018’}
PL/SQL It stands for Procedural Language SQL. It is a programming language where we
incorporate SQL queries inside program and hence it also known as Embedded SQL as we
embed SQL queries inside a program.
A PL/SQL consists of different types of sub programs which are known as blocks. A
block is basically of two types namely: anonymous blocks (un-named blocks) and named blocks.
A named block is further categorized into procedure, function and package.
A block is either named or un-named; the basic structure of a block is as follows
Set serveroutput on
Declare
Variables are declared and specified for their data type
.
.
.
Begin
Executable part of program using loops, control statements calling functions and
procedure etc
.
.
.
.
Exception
We specify different error handling statements during execution of a program
.
.
End;/
A PL/SQL block starts with declare section which is optional also ie if we do not require
any additional variable then it is not needed and program will start directly with begin section. In
declare we specify all variable which is needed, which can be a simple variable or complex
variable using user defined types or system defined type such as %columntype or %rowtype.
Begin section is the actual section of program which is mandatory. In this section we
write all the logic of the program using different programming constructs which may extend to
hundreds or thousands of lines.
Exception is the error handling section and it is optional ie if run time errors, which are
actually called exceptions, are required to be handled then we use exception section.
End is last line in the program which terminates a PL/SQL program and it is mandatory.
It must be followed by ; and /, where front slash passes a signal to Oracle Server to execute the
program.
Before starting of block set serveroutput on passes a message to Oracle Server to reserve
space in main memory which is by default 2000 bytes.
If we want to read data from user then it has a simple utility given as follows
Varname := &varname;
Where in PL/SQL all scalar assignments are to be preceded by : and & is input operator.
If we want output data on the monitor then the function used is as follows
Dbms_output.put_line(‘Messesge’|| ‘Message’|| varname1|| varname2||…)
If any message is to be displayed then it is enclosed inside single quotes and variable
values without single quote. All the outputs to be separated by ||.
The environment in which PL/SQL programs can be written is SQLPLUS.
Prog1: Write a block to display the “Welcome to PL/SQL programming”

Set serveroutput on;


Begin
Dbms_output.put_line(‘Welcome to PL/SQL programming’);
End;
/

NOTE: The above program is of type un-named block and hence it can’t be saved and it can be
written and executed once. If we close this block then it will not exist in the system. If we require
program to be saved for future then we must write named block so that we can save it.
Pgm2: Write a block to read 2 integers from user and print their addition.
Set serveroutput on;
Declare
a integer;
b integer;
Begin
a := &a;
b := &b;
dbms_output.put_line(‘Sum of ’||a||‘and ’|| b||‘is’||a+b);
End;
/
Op
Enter any two integers:
5
6
Sum of 5 and 6 is 13
Above program input taken in declare section itself
Set serveroutput on;
Declare
a integer := &a;
b integer := &b;
Begin
dbms_output.put_line(‘Sum of ’||a||‘and ’|| b||‘is’||a+b);
End;/
Pgm3: Write a program to read 2 integers and display their product
Set serveroutput on;
Declare
a integer :=&a;
b integer :=&b;
Begin
Dbms_output.put_line(‘The product of ’||a||‘ and ’||b||‘ is ’||a*b);
End;/

IF – Else It is a conditional control statement used to control flow of program and its syntax
is given as follows
i> if condn then
………..
………..
end if;
ii> if condn then
…………….
…………….
elif condn then ( In oracle else if is taken as elif)
………..
Else
…………
End if
End if;
Pgm4> Write a block to read an integer from user check if it is even or odd and display a proper
output.

Declare
i integer := &i;
Begin
if (i mod 2 = 0) then
dbms_output.Put_line(‘ even’);
else
dbms_output.Put_line(‘ odd’);
end if;
end;
/
Pgm5> Write a block to read an integer between 1 and 10 and display it in word format. If no is
not in the range then display that no is out of range.
Declare
i integer := &i;
Begin
if i = 1 then
dbms_output.put_line(‘ One ‘);
elif i = 2 then
dbms_output.put_line(‘ Two ‘);
elif i = 3 then
dbms_output.put_line(‘ Three ‘);
elif i = 4 then
dbms_output.put_line(‘ Four ‘);
elif i = 5 then
dbms_output.put_line(‘ Five ‘);
elif i = 6 then
dbms_output.put_line(‘ Six ‘);
elif i = 7 then
dbms_output.put_line(‘ Seven ‘);
elif i = 8 then
dbms_output.put_line(‘ Eight ‘);
elif i = 9 then
dbms_output.put_line(‘ Nine ‘);
elif i = 10 then
dbms_output.put_line(‘ Ten ‘);
else
dbms_output.put_line(‘ Integer is out of range’);
end if;
end;/
for It is an iterative statement used to repeat part of a program again & again, its syntax is
given as follows
for var_name in start_value .. end_value (range)
loop
………….
………….
End loop;
Eg. for i in 1..10
loop
…..
….
end loop;
Pgm6> Write a block to print all even nos from 1 to 100
Declare
i integer;
Begin
for i in 1 .. 100
loop
if (i mod 2 = 0)
dbms_output.put_line(i);
end if;
end loop;
end;/
while It is an iterative statement used to repeat part of a program again & again, its syntax is
given as follows
while condn
loop
…….
…….
End loop ;
Prgm7: Prgm6 with while loop
Declare
i integer := 1;
Begin
While i < 101
loop
if (i mod 2 = 0)
dbms_output.put_line(i);
end if;
i := i+1;
end loop;
end;/
Loop with exit –when & loop with if – then-exit Its syntax is given as follows
Loop
Exit when codn;
…….
……..
End loop;

Loop
If condn then
Exit;
End if;
………………
………………
End loop;
Prgm8: Prgm 6 with loop exit - when
Declare
i integer := 1;
Begin
Loop
Exit when i > 100;
if (i mod 2 = 0)
dbms_output.put_line(i);
end if;
i := i+1;
end loop;
end;/
Prgm9: Prgm 6 with loop if – then – exit
Declare
i integer := 1;
Begin
Loop
If i > 100 then
Exit;
End if;
if (i mod 2 = 0)
dbms_output.put_line(i);
end if;
i := i+1;
end loop;
end;/
Embedding SQL Queries inside a program SQL query of DML or DTL type can be included
inside a program in Begin Section. We can also include select query in Declare section if we are
creating cursors. To take queries in begin section we require additional variables in query to store
the values of data selected by query, consider an example:
Pgm10 Write a pgm to find out employee name and date of join for the salesperson with id as
101 and display the values.
Declare
name varchar2(20); --data type has to be same as we took into table salserep
jdate date;
Begin
Select empname, joindate into name, jdate
From salesreps
Where empid = 101;
Dbms_output.put_line(‘ Name and join date of salesperson is’|| name|| jdate);
End;
/
To assign data types of columns from a table to a variable in program requires the data type to be
remembered which is a difficult and hence database has provided in – built types such
%columntype and %rowtype, which can be used to assign the data types to variables.
.columnname%type It is used to assign data type of a specific column from table. It can be used
when we want a column value to be selected and stored in a variable and its syntax is given as
follows
varname tablename.columnname%type;
eg. name salesreps.empname%type;
%rowtype It is used to assign data types associated in whole row of a table to a variable and
hence such variables are known as row type variable. It can be used when we want to select the
whole row with select * and assign to a variable and its syntax is given as follows
varname tablename%rowtype;
eg. etype salesreps%rowtype;
etype now is called a row variable which can store all columns of a table with one row at a time
and if we want to access individual column names then we can write etype.columnname example
etype.ename, etype.sales etc.
Pgm11. Write a program to get the customer name and credit limit of the customer with id 111
and print the values.
Declare
cname customer.name%type;
climit customer.creditlimit%type;
Begin
Select name, creditlimit into cname, climit
From customers
Where custid = 111;
Dbms_output.put_line(‘The name and credit limit of customer 111 is’||cname||climit);
End;
/
Pgm12. Write a program to select the detail of employee no 101 and print the name, date of join
sales & target of that employee.
Declare
etype salesreps%rowtype;
Begin
Select * into etype
from Salesreps
Where empid = 101;
Dbms_output.put_line(‘The name, date of join, sales and target of employee is
’||etype.name||’ ‘||etype.joindate|| ‘ ‘||etype.sales|| ‘ ‘||etype.target);
End;/
User defined types If we want to create complex types as per user requirement and select the
record from a table and store into the types then we require user defined types. Its syntax is given
as follows
Declare
type typename as
(
varname1 datatype,
varnzme2 datatype,
.
.
);
ojectname typename;
.
.
End;/
Now in the begin section the object created can be used to process the records.

Prg13: Write a block to create a user defined type with columns eid, ename, esales & etarget
then store the values of employee with id 101 and print the records.

Declare
type etype as
( eid salesreps.empid%type,
ename salesreps.name%type,
esales salesreps.sales%type,
etarget salesrerps.target%type
);
e etype;
Begin
Select empid, name, sales, target into e
From salesreps
Where empid = 101;
Dbms_output.put_line(‘Detials of employee 101 is ’||e.eid||’ ‘||e.ename||’ ‘||e.esales||’
‘||e.etarget);
End;
/
Case Case expression is used to add multiple branches in the program and it is similar to
if..then..else but provides more flexibility in terms adding conditions and creating branches. Its
syntax is given as follows
1> case varname
when value1 then
…………….
when value2 then
…………….
when value3 then
…………….
.
.
else
…………..
End case;
2> case
when condn1 then
…………….
When condn2 then
………….
.
.
Else
…………
End case;
Pgm14: Write a program to read in integer from user and use case statement to print no in words
if it is within 1 to 10 otherwise print no out of range.
Declare
i integer;
Begin
i := &i;
case i
when 1 then
dbms_output.put_line(‘One’);
when 2 then
dbms_output.put_line(‘Two’);
when 3 then
dbms_output.put_line(‘Three’);
when 4 then
dbms_output.put_line(‘Four’);
when 5 then
dbms_output.put_line(‘Five’);
when 6 then
dbms_output.put_line(‘Six’);
when 7 then
dbms_output.put_line(‘Seven’);
when 8 then
dbms_output.put_line(‘Eight’);
when 9 then
dbms_output.put_line(‘Nine’);
when 10 then
dbms_output.put_line(‘Ten’);
else
dbms_output.put_line(‘Number out of range’);
end case;
end;/
Pgm15: Prog14 with alternate case statement.
Declare
i integer;
Begin
i := &i;
case
when i = 1 then
dbms_output.put_line(‘One’);
when i = 2 then
dbms_output.put_line(‘Two’);
when i = 3 then
dbms_output.put_line(‘Three’);
when i = 4 then
dbms_output.put_line(‘Four’);
when i = 5 then
dbms_output.put_line(‘Five’);
when i = 6 then
dbms_output.put_line(‘Six’);
when i = 7 then
dbms_output.put_line(‘Seven’);
when i = 8 then
dbms_output.put_line(‘Eight’);
when i = 9 then
dbms_output.put_line(‘Nine’);
when i = 10 then
dbms_output.put_line(‘Ten’);
else
dbms_output.put_line(‘Number out of range’);
end case;
end;/
Pgm16: Write a program to read an integer and check if it is within 1 to 9 then print single digit
number or else if it is within 10 to 99 then print two digit number else if it is within 100 to 999
then print three digit number else if it is within 1000 to 9999 then print four digit number
otherwise print number is out of range
Declare
i integer;
Begin
i := &i;
case
when (i >= 1 and i <= 9) then
dbms_output.put_line(‘Single digit number’);
when (i >= 10 and i <= 99) then
dbms_output.put_line(‘Two digit number’);
when (i >= 100 and i <= 999) then
dbms_output.put_line(‘Three digit number’);
when (i >= 1000 and i <= 9999) then
dbms_output.put_line(‘Four digit number’);
else
dbms_out.put_line(‘Number is out of range’);
end case;
end;/
Exception The run time error that may occur due to logical problems in the program while
program is running is called Exception or logical errors. When such error occurs then program
terminates abruptly without giving a proper message and hence the user will not come to know
what is wrong in the program.
So to handle such errors with proper display of message is called exception handling.
When exception handling is done then errors are captured by exception handling statement and
then display a proper response and then user can understand the problem with the program and
accordingly can resolve.
An exception has 3 different steps for implementation in the program which are Defining
exception, raising exception and Handling exception.
Exceptions are of mainly two types: System Defined Exception and User Defined
Exception.
System Defined Exception The exceptions which are known to the system are known as
system defined exceptions and hence they are also referred as pre defined exceptions. Such
exceptions are again of two different types namely Named System Exceptions & Un – named
system Exceptions.
Named System Exception These types of exceptions are defined and raised by system itself
with a certain name given to them by the system. When such exception occurs, system raises it
with name assigned to it, which we can use to handle; some of named system exceptions are
given as follows:
i> NO_DATA_FOUND
It is raised when there are no rows selected by the query.
ii> ZERO_DIVIDE
It is raised when a number is divided by 0, as a no divided by 0 is not defined.
iii> TOO_MANY_ROWS
It is raised when a query returns multiple rows to be stored into a type name.
iv> INVALID_CURSOR
It is raised when cursor name is written incorrectly.
v> CURSOR_ALREADY_OPEN
It is raised when we try to open a cursor which is already open.
vi> Others
It is raised when any unknown error may occur.
The syntax to use a named system defined exception is as follows
Declare
------------

Begin
------------

Exception
When exception_name1 then
Dbms_output.put_line(‘Message’);
When exception_name2 then
Dbms_output.put_line(‘Message’);
` ------
End;/
Prg17: Write a program to illustrate use of NO_DATA_FOUND & TO_MANY_ROWS
exceptions.
Declare
erec1 salesreps%rowtype;
erec2 salesreps%rowtype;
Begin
select * into erec1
from salesreps
where sales > 5000;
dbms_output.put_line(‘ Name and sales of employee having sales more than 5000 is’||
erec1.name||’ ‘||erec1.sales);
select * into erec2
from salesreps
where empid = 100;
dbms_output.put_line(‘ Name and sales of employee with id 100 is’||erec2.name||’ ‘||
erec2.sales);
Exception
when to_many_rows then
dbms_output.put_line(‘Multiple rows has been returned by query so you can use
cursors instead of record type’);
when no_data_found then
dbms_output.put_line(‘ There is no record with id 100’);
when others then
dbms_output.put_line(‘An unknown error occurred’);
end;/

Un-named System Exceptions This type of exception is also defined by the system by defining
an error code from -20000 to -20999 to the error that may occur without any name assigned to
error. This type of exception can be used by assigning name to the error code in declare section.
The syntax to use un-named system exception is as follows
Declare
------
PRAGMA Exception_Init(exception_name, -errorcode);
Begin
-----
-----

Exception
When exception_name then
Dbms_output.put_line(‘Message’);
-----

End;/
Pgm18: Write a program to delete a row from salesreps table having its child row in other tables
and illustrate the un-named system error.
Declare
PRAGMA Exception_Init(Child_Row_Except, -20999);
Begin
Delete
From Salesreps
Where empid = 101;
Exception
When child_row_except then
Dbms_output.put_line(‘Row can’t be deleted as it has a child row’);
End;/
User defined exception These type of exception are to be defined, raised and handled by the
programmer and hence it is called user defined exception. There can be different situation during
transactions which are not known to database software as it may be domain dependent and a
programmer has to identify such errors and has to do implementation, where programmer will
have to define error in declare section then raise into begin section with condition and handle
into exception section. The syntax to implement user defined exception is given as follows
Declare
Exception_name EXCEPTION;
-------
Begin
--------
If condn then
Rasie Exception_name;
End if;
--------
---------
Exception
When Exception_name
Dbms_output.put_line(‘Message’);
When others
Dbms_output.put_line(‘Message’);
End;/
Prg19: Write a program to delete rows from table salesreps if sales is equal to 0. Use user
defined exception to print a proper message if no rows are deleted.
Declare
No_rows_deleted Exception;
Begin
Delete
From salesreps
Where sales = 0;
If SQL%NOTFOUND – implicit cursor
Raise No_rows_deleted;
Exception
When No_rows_deleted then
Dbms_output.put_line(‘There is no employee with sales as 0’);
Or
Riase_Appication_error(‘There is no employee with sales as 0’);
End;/
Cursors Cursors are defined as database objects used to iterate over the rows of a table
defined in declare section of block. When it is defined, it extracts the rows from the table and
stores in the buffer reserved by set serveroutput on and moves from the first row towards the last
reserved by the cursor. Hence it is used to mark the rows from as current row in the cursor and
can be accessed by it one by one. It is of two different types namely implicit cursor and explicit
cursor.
Implicit cursor This type of cursor is created and destroyed by the database system on its own
for every DML statement such as insert, delete, update etc. When DML statements are executed,
implicit cursor is created by the database and is used to track the no of rows affected. The name
of this cursor is SQL. This SQL cursor has certain attributes which are used to track rows
affected, which are as follows:
i> %FOUND
ii> %NOTFOUND
iii> %ISOPEN
iv> %ROWCOUNT
The above cursors can be used along with the cursor name as SQL%attribute, eg SQL%found
etc.
The meaning of cursor attributes are as follows
%FOUND returns true if at least one row is found otherwise false
%NOTFOUND returns true if no row is found otherwise false
%ISOPEN returns true if cursor is already open otherwise false
%ROWCOUNT returns the total no of rows affected by DML statement.
Prg20: Write a program to increase target of employees of 25% if their sales is more than target.
Also print the total no of rows updated if there is any employee satisfying the condition.
Declare
No_of_rows_updated integer;
Begin
Update salesreps
Set target = target + target*0.25
Where sales > target;
If SQL%FOUND then
No_of_rows_updated := SQL%ROWCOUNT;
Dbms_output.put_line(‘Total no of rows updated are ’||No_of_rows_updated);
Else
Dbms_output.put_line(‘There are no employees having sales above target’);
End if;
End;/
Note:- %ISOPEN plays the role in case of explicit cursors.
Explicit cursors This type of cursor is to be created and destroyed by the program explicitly.
The explicit cursors are to be defined in declare section with a query and then it has to be opened
for use in begin section and then can be used in begin section. Once it has been used then it must
be closed before it is re opened and hence a cursor can be opened and closed multiple times. The
attributes that can be used with explicit cursors are same as in case of implicit cursors except
%ISOPEN. The syntax to create explicit cursor is given as follows
Declare
Cursor cursor_name is|as
Select query with all the clauses and complexities.
Rec_type Tablename%rowtype;(table name will be same table taken in query)
Begin
Open cursor_name;
Loop
Fetch cursor_name in Rec_type;
-------
-------
End loop;
Close cursor_name
-----
-----
End;
Or using cursor in begin section with for loop
Begin
Open cursor_name;
For Rec_type in cursor_name
loop
-------
-------
End loop;
Close cursor_name;
-----
-----
End;
Prg21: Write a program to create a cursor with all employees with sales more than target and use
this cursor to print the name, sales and target of employee.
Declare
Cursor emp_cur is
Select * from salesreps
Where sales>target;
Emp_rec salesreps%rowtype;
Begin
Open emp_cur;
Loop
Fetch emp_cur in emp_rec
Dbms_out.put_line(‘Name, sales & target of employee is ’||
emp_rec.name||‘ ’||emp_rec.sales||‘ ’||emp_rec.target);
End loop;
Close emp_cur;
End;
/
Prg22: Write a program to create a cursor for employees with their id, name, date of join, sales,
target and their order id, order date and amount print the name of employee if there is any having
their order amount more than their target.
Declare
Cursor emp_ord is
Select empid, name, joindate, sales, target, ordid, date, amt
From salesreps, orders
Where rep = empid;
Emp_ord_rec emp_ord%rowtype;
Begin
Open emp_ord;
For emp_ord_rec in emp_ord
Loop
If (emp_ord_rec.amt > emp_ord_rec.target) then
Dbms_output.put_line(‘Name of employee is ’||emp_ord_rec.name);
End if;
End loop
Close emp_cur;
End;
/
Above program with while loop
Declare
Cursor emp_ord is
Select empid, name, joindate, sales, target, ordid, date, amt
From salesreps, orders
Where rep = empid;
Emp_ord_rec emp_ord%rowtype;
Begin
Open emp_ord;
While emp_cur%FOUND
Loop
Fetch emp_cur in emp_ord_rec;
If (emp_ord_rec.amt > emp_ord_rec.target) then
Dbms_output.put_line(‘Name of employee is ’||emp_ord_rec.name);
End if;
End loop;
Dbms_output.put_line(‘Total no of employees with amount more than target is ’||
emp_cur%ROWCOUNT);
Close emp_cur;
End;
/

Named Blocks Named blocks are functions, procedures and packages. These blocks also
have similar structure as it is in case of un-named blocks. All the features that we have seen in
un-named blocks are also applicable in named blocks. Only the difference is that a named block
will start by assigning a name to it and since it is given name so it can be stored for future uses
and hence also known as stored procedures. Its syntax is given as follows:
Procedure
Create [or replace] procedure proc_name( paraname1 [mode] datatype, ….) is|as
Varname datatype;
.
.
Begin
.
.
.
Exception
.
.
End proc_name;
/
The above syntax consist of a similar structure as in case of un named blocks with additional
thing of specifying name and parameters, so
Create [or replace] is used to create a new procedure where [or replace] is optional which
will be needed if we want to over write an existing procedure, then it is followed by keyword
procedure and procedure name to be given by user with parameters, where parameter has its
name data type and mode of it, where it has following modes
in this mode of parameter is used to pass the values inside procedure with the condition such
parameters can not be modified by the procedure and hence behaves as constant.

out this mode of parameter is used to pass the values inside the procedure and can also be
modified by the procedure. Also it can be used to return the values back to the block from where
the procedure was called.

inout this mode of parameter has features of both in & out parameters. If no mode is specified
the by default mode will be out.
Lastly procedure is name is followed by is|as where either is or as can be taken to create the
procedure.
Once procedure is created then it will be saved in database as any other object like table. When it
is to be executed then it can be called from another block.

Prg: Write a block to call a procedure with parameter as eid and find out the name sales & target
of employee and print the output.
Create procedure find_emp_det( eid salesreps.empid%type) is
ename salesreps.name%type;
esales salesreps.sales%type;
etarget salesreps.target%type;
Begin
Select name, sales, target into ename, esales, etarget
From salesreps
Where empid = eid;
Dbms_output.put_line(‘Name, sales % target of ’||eid||‘ is’||ename||‘ ’||esales||‘ ’|| etarget’);
End find_emp_det;
/
Op: procedure created.
To execute above procedure it is to be called from some other block
Declare
eid salesreps.empid%type;
Begin
Eid :=&eid;
Find_emp_det(eid);
End;
/
Functions
Create [or replace] function fun_name(parameter [mode] datatype, ….) returns
datatype is|as
Variable datatype;
.
.
Begin
.
.
.
Exception
.
.
End fun_name;
/
The additional thing in function as compare to procedure is that function returns a value
explicitly which is in addition to out mode of variables which can also return value.

Prg: Write a block to call a function with parameter as eid and find out the total order amount
and return it to the block again to display output.
Create function find_tot_ordamt( eid salesreps.empid%type) returns orders.amt%type is
tot_amt_ord orders.amt%type;
Begin
Select sum(amt) into tot_amt_ord
From orders
Where rep = eid;
return tot_amt_ord;
End find_tot_ordamt;
/
To execute above function it is to be called from some other block
Declare
eid salesreps.empid%type;
tot_amt_ord orders.amt%type;
Begin
eid :=&eid;
tot_amt_ord := find_tot_ordamt(eid);
dbms_output.put_line(‘total order amount of ’||eid||‘ is ’||tot_amt_ord);
End;
/
Package It is defined as a wrapper used to encapsulate (bundle) various functions & procedures
together inside a single unit so that an application can be developed and stored inside the system
for future uses.
A package is created in two different steps which are
i> Package Specification
ii> Package body definition
Package Specification It is defined as an interface where we specify about different data
types, function and procedures. In this we simply specify functions and procedures with their
data types and return types and their implementation is specified inside package body definition.
The syntax is given as follows
Create [or replace] package package_name(para1 [mode] datatype, ………) is|as
Varname1 datatype;
.
.
Procedure procedure_name(para1 [mode] datatype, ……);
.
.
Function function_name(para1 [mode] datatype, ……) returns datatype;
.
.
End package_name;
/
Above syntax shows that we can only declare different variable and stored procedures inside
package specification.
After package specification is done then package needs its implementation by defining package
body and its syntax is given as follws
Create [or replace] package_name_body(para1 [mode] datatype, ………) is|as
Varname1 datatype;
.
.
Procedure procedure_name(para1 [mode] datatype, ……) is|as
Varname datatype;
.
.
Begin
.
.
Exception
.
.
End procedure_name;
.
. - -more procedures
Function function_name(para1 [mode] datatype, ……) returns datatype is|as
Varname datatype;
.
.
Begin
.
.
Exception
.
.
End function_name;
.
. - -more functions
End package_name_body;
/
Note: The no of variables, function and procedure has to be same in specification as well in
body.
What is a Trigger?
A trigger is a pl/sql block structure which is fired when a DML statements like Insert, Delete,
Update is executed on a database table. A trigger is triggered automatically when an associated
DML statement is executed. It works on E-C-A model which is known as Event- Condition-
Action, where event is any event that may occur in database and based on certain condition an
activity may be fired which is called action, in this model sometimes condition happens to be
optional.

Syntax of Triggers

The Syntax for creating a trigger is:

CREATE [OR REPLACE ] TRIGGER trigger_name


{BEFORE | AFTER | INSTEAD OF }
{INSERT [OR] | UPDATE [OR] | DELETE}
[OF col_name]
ON table_name/view_name
[REFERENCING OLD AS o NEW AS n]
[FOR EACH ROW]
WHEN (condition)
BEGIN
--- sql statements
END;

CREATE [OR REPLACE ] TRIGGER trigger_name - This clause creates a trigger with the given
name or overwrites an existing trigger with the same name.

{BEFORE | AFTER | INSTEAD OF } - This clause indicates at what time should the trigger get
fired. i.e for example: before or after updating a table. INSTEAD OF is used to create a
trigger on a view. Before and after cannot be used to create a trigger on a view.

{INSERT [OR] | UPDATE [OR] | DELETE} - This clause determines the triggering event. More
than one triggering events can be used together separated by OR keyword. The trigger gets
fired at all the specified triggering event.

[OF col_name] - This clause is used with update triggers. This clause is used when you want
to trigger an event only when a specific column is updated.

[ON table_name/view_name] - This clause identifies the name of the table or view to which
the trigger is associated.

[REFERENCING OLD AS o NEW AS n] - This clause is used to reference the old and new
values of the data being changed. By default, you reference the values as :old.column_name
or :new.column_name. The reference names can also be changed from old (or new) to any
other user-defined name. You cannot reference old values when inserting a record, or new
values when deleting a record, because they do not exist.
[FOR EACH ROW] - This clause is used to determine whether a trigger must fire when each
row gets affected ( i.e. a Row Level Trigger) or just once when the entire sql statement is
executed(i.e.statement level Trigger).

WHEN (condition) - This clause is valid only for row level triggers. The trigger is fired only for
rows that satisfy the condition specified.

Begin…End will have the logic for the actions to be executed based on the event specified
before it.

For Example: The price of a product changes constantly. It is important to maintain the history
of the prices of the products.

We can create a trigger to update the 'product_price_history' table when the price of the
product is updated in the 'product' table.

1) Create the 'product' table and 'product_price_history' table

CREATE TABLE product_price_history


(product_id number(4),
product_name varchar2(32),
supplier_name varchar2(32),
unit_price number(7,2) );

CREATE TABLE product


(product_id number(5),
product_name varchar2(32),
supplier_name varchar2(32),
unit_price number(7,2) );

2) Create the price_history_trigger and execute it.

CREATE or REPLACE TRIGGER price_history_trigger


BEFORE UPDATE OF unit_price
ON product
FOR EACH ROW
BEGIN
INSERT INTO product_price_history
VALUES (:old.product_id,
:old.product_name,
:old.supplier_name,
:old.unit_price);
END; /

3) Lets update the price of a product.

UPDATE PRODUCT SET unit_price = 800 WHERE product_id = 100


Once the above update query is executed, the trigger fires and updates the
'product_price_history' table.

4)If you ROLLBACK the transaction before committing to the database, the data inserted to the
table is also rolled back.

Types of PL/SQL Triggers


There are two types of triggers based on the which level it is triggered.
1) Row level trigger - An event is triggered for each row upated, inserted or deleted.
2) Statement level trigger - An event is triggered for each sql statement executed.

PL/SQL Trigger Execution Hierarchy


The following hierarchy is followed when a trigger is fired.
1) BEFORE statement trigger fires first.
2) Next BEFORE row level trigger fires, once for each row affected.
3) Then AFTER row level trigger fires once for each affected row. This event will alternates
between BEFORE and AFTER row level triggers.
4) Finally the AFTER statement level trigger fires.

For Example: Let's create a table 'product_check' which we can use to store messages when
triggers are fired.

CREATE TABLE product


(Message varchar2(50),
Current_Date number(32)
);

Let's create a BEFORE and AFTER statement and row level triggers for the product table.

1) BEFORE UPDATE, Statement Level: This trigger will insert a record into the table
'product_check' before a sql update statement is executed, at the statement level.

CREATE or REPLACE TRIGGER Before_Update_Stat_product


BEFORE
UPDATE ON product
Begin
INSERT INTO product_check
Values('Before update, statement level',sysdate);
END; /

2) BEFORE UPDATE, Row Level: This trigger will insert a record into the table 'product_check'
before each row is updated.
CREATE or REPLACE TRIGGER Before_Upddate_Row_product
BEFORE
UPDATE ON product
FOR EACH ROW
BEGIN
INSERT INTO product_check
Values('Before update row level',sysdate);
END; /

3) AFTER UPDATE, Statement Level: This trigger will insert a record into the table
'product_check' after a sql update statement is executed, at the statement level.

CREATE or REPLACE TRIGGER After_Update_Stat_product


AFTER
UPDATE ON product
BEGIN
INSERT INTO product_check
Values('After update, statement level', sysdate);
End; /

4) AFTER UPDATE, Row Level: This trigger will insert a record into the table 'product_check'
after each row is updated.

CREATE or REPLACE TRIGGER After_Update_Row_product


AFTER
insert On product
FOR EACH ROW
BEGIN
INSERT INTO product_check
Values('After update, Row level',sysdate);
END; /

Now lets execute a update statement on table product.

UPDATE PRODUCT SET unit_price = 800


WHERE product_id in (100,101);

Lets check the data in 'product_check' table to see the order in which the trigger is fired.

SELECT * FROM product_check;

Output:

Mesage                                             Current_Date

------------------------------------------------------------

Before update, statement level          26-Nov-2008


Before update, row level                    26-Nov-2008
After update, Row level                     26-Nov-2008
Before update, row level                    26-Nov-2008
After update, Row level                     26-Nov-2008
After update, statement level            26-Nov-2008

The above result shows 'before update' and 'after update' row level events have occured twice,
since two records were updated. But 'before update' and 'after update' statement level events
are fired only once per sql statement.

The above rules apply similarly for INSERT and DELETE statements.

How To know Information about Triggers.


We can use the data dictionary view 'USER_TRIGGERS' to obtain information about any trigger.

The below statement shows the structure of the view 'USER_TRIGGERS'

DESC USER_TRIGGERS;

NAME                              Type

--------------------------------------------------------

TRIGGER_NAME                 VARCHAR2(30)


TRIGGER_TYPE                  VARCHAR2(16)
TRIGGER_EVENT                VARCHAR2(75)
TABLE_OWNER                  VARCHAR2(30)
BASE_OBJECT_TYPE           VARCHAR2(16)
TABLE_NAME                     VARCHAR2(30)
COLUMN_NAME                  VARCHAR2(4000)
REFERENCING_NAMES        VARCHAR2(128)
WHEN_CLAUSE                  VARCHAR2(4000)
STATUS                            VARCHAR2(8)
DESCRIPTION                    VARCHAR2(4000)
ACTION_TYPE                   VARCHAR2(11)
TRIGGER_BODY                 LONG

This view stores information about header and body of the trigger.

SELECT * FROM user_triggers WHERE trigger_name = 'Before_Update_Stat_product';

The above sql query provides the header and body of the trigger
'Before_Update_Stat_product'.
You can drop a trigger using the following command.

DROP TRIGGER trigger_name;

CYCLIC CASCADING in a TRIGGER


This is an undesirable situation where more than one trigger enter into an infinite loop. while
creating a trigger we should ensure the such a situtation does not exist.

The below example shows how Trigger's can enter into cyclic cascading.
Let's consider we have two tables 'abc' and 'xyz'. Two triggers are created.
1) The INSERT Trigger, triggerA on table 'abc' issues an UPDATE on table 'xyz'.
2) The UPDATE Trigger, triggerB on table 'xyz' issues an INSERT on table 'abc'.

In such a situation, when there is a row inserted in table 'abc', triggerA fires and will update
table 'xyz'.
When the table 'xyz' is updated, triggerB fires and will insert a row in table 'abc'.
This cyclic situation continues and will enter into an infinite loop, which will crash the database.

SEQUENCE It is a database object used to create unique values.

The CREATE SEQUENCE statement allows you to create a new sequence in the database.


Here is the basic syntax of the CREATE SEQUENCE statement:

CREATE [or replace] SEQUENCE schema_name.sequence_name


[INCREMENT BY interval]
[START WITH first_number]
[MAXVALUE max_value | NOMAXVALUE]
[MINVALUE min_value | NOMINVALUE]
[CYCLE | NOCYCLE]
[CACHE cache_size | NOCACHE]
[ORDER | NOORDER];

CREATE SEQUENCE

Specify the name of the sequence after the CREATE SEQUENCE keywords. If you want to create
a sequence in a specific schema, you can specify the schema name in along with the sequence
name.

INCREMENT BY

Specify the interval between sequence numbers after the INCREMENT BY keyword.


The interval can have less than 28 digits. It also must be less than MAXVALUE - MINVALUE.
If the interval is positive, the sequence is ascending e.g., 1,2,3,…
If the interval is negative, the sequence is descending e.g., -1, -2, -3 …
The default value of interval is 1.

START WITH

Specify the first number in the sequence.

The default value of the first number is the minimum value of the sequence for an ascending
sequence and maximum value of the sequence for a descending sequence.

MAXVALUE

Specify the maximum value of the sequence.

The max_value must be equal to or greater than first_number specify after the START


WITH keywords.

NOMAXVALUE

Use NOMAXVALUE to denote a maximum value of 10^27 for an ascending sequence or -1 for a


descending sequence. Oracle uses this option as the default.

MINVALUE

Specify the minimum value of the sequence.

The min_value must be less than or equal to the first_number and must be less


than max_value.

NOMINVALUE

Use NOMINVALUE to indicate a minimum value of 1 for an ascending sequence or -10^26 for a


descending sequence. This is the default.

CYCLE

Use CYCLE to allow the sequence to generate value after it reaches the limit, min value for a
descending sequence and max value for an ascending sequence.
When an ascending sequence reaches its maximum value, it generates the minimum value.

On the other hand, when a descending sequence reaches its minimum value, it generates the
maximum value.
NOCYCLE

Use NOCYCLE if you want the sequence to stop generating the next value when it reaches its
limit. This is the default.

CACHE

Specify the number of sequence values that Oracle will preallocate and keep in the memory for
faster access.

The minimum of the cache size is 2. The maximum value of the cache size is based on this
formula:

(CEIL (MAXVALUE - MINVALUE)) / ABS (INCREMENT)


In case of a system failure event, you will lose all cached sequence values that have not been
used in committed SQL statements.

ORDER

Use ORDER to ensure that Oracle will generate the sequence numbers in order of request.
This option is useful if you are using Oracle Real Application Clusters. When you are using
exclusive mode, then Oracle will always generate sequence numbers in order.

NOORDER

Use NOORDER if you do not want to ensure Oracle to generate sequence numbers in order of
request. This option is the default.
Eg create a sequence for generating unique employee ids for the table salesreps. The sequence
is to start with 2001 and range to be a 4 digit no.
Create sequence unique_empid
Start with 2001
Increment by 1
Maxvalue 9999
Minvalue 1000
Cycle
Cache 50
Order;
Now to insert the unique values as value of primary key in table salesreps we use cur_val as
follows
Insert into salesreps
Values(unique_empid.cur_val,.....,….,…………);
Index Indexes are the database objects which can be created by user into a table for optimizing
the search to be performed on the fields other than primary keys as system creates index on its
primary key. Its syntax is as follows

Create index ind_name


on table_name using column_name;
Table name is account
Create index unique_mob
On account using mobile;
Transaction A transaction is defined as set of SQL statements that performs a logical unit of
work or it is defined as set of SQL statements that takes database from one consistent state to
another consistent state.
A transaction can be defined as a group of tasks. A single task is the minimum
processing unit which cannot be divided further.
Let’s take an example of a simple transaction. Suppose a bank employee transfers
Rs 500 from A's account to B's account. This very simple and small transaction
involves several low-level tasks.
Suppose initially balance of A was 2000 and B was 2500
At start bal(A) + bal(b) = 4500
A’s Account
Open_Account(A)
Old_Balance = A.balance
New_Balance = Old_Balance - 500
A.balance = New_Balance
Close_Account(A)
B’s Account
Open_Account(B)
Old_Balance = B.balance
New_Balance = Old_Balance + 500
B.balance = New_Balance
Close_Account(B)
At end if bal(A) + bal(b) =4500 then we that it is consistent

A transaction must satisfy ACID Properties


A transaction is a very small unit of a program and it may contain several low level
tasks. A transaction in a database system must
maintain Atomicity, Consistency, Isolation, and Durability − commonly known as
ACID properties − in order to ensure accuracy, completeness, and data integrity.
 Atomicity − This property states that a transaction must be treated as an
atomic unit, that is, either all of its operations are executed or none. There
must be no state in a database where a transaction is left partially
completed. States should be defined either before the execution of the
transaction or after the execution/abortion/failure of the transaction. To
maintain this property transaction must execute either commit if transaction
completes successfully or rollback if transaction fails in between.
 Consistency − The database must remain in a consistent state after any
transaction. No transaction should have any adverse effect on the data
residing in the database. If the database was in a consistent state before the
execution of a transaction, it must remain consistent after the execution of
the transaction as well.
 Durability − The database should be durable enough to hold all its latest
updates even if the system fails or restarts. If a transaction updates a chunk
of data in a database and commits, then the database will hold the modified
data. If a transaction commits but the system fails before the data could be
written on to the disk, then that data will be updated once the system springs
back into action.
 Isolation − In a database system where more than one transaction are being
executed simultaneously and in parallel, the property of isolation states that
all the transactions will be carried out and executed as if it is the only
transaction in the system. No transaction will affect the existence of any
other transaction.

Serializability
When multiple transactions are being executed by the operating system in a
multiprogramming environment, there are possibilities that instructions of one
transactions are interleaved with some other transaction.
 Schedule − A chronological execution sequence of a transaction is called a
schedule. A schedule can have many transactions in it, each comprising of a
number of instructions/tasks.
 Serial Schedule − It is a schedule in which transactions are aligned in such a
way that one transaction is executed first. When the first transaction
completes its cycle, then the next transaction is executed. Transactions are
ordered one after the other. This type of schedule is called a serial schedule,
as transactions are executed in a serial manner.
In a multi-transaction environment, serial schedules are considered as a
benchmark. The execution sequence of an instruction in a transaction cannot be
changed, but two transactions can have their instructions executed in a random
fashion. This execution does no harm if two transactions are mutually independent
and working on different segments of data; but in case these two transactions are
working on the same data, then the results may vary. This ever-varying result may
bring the database to an inconsistent state.
To resolve this problem, we allow parallel execution of a transaction schedule, if its
transactions are either serializable or have some equivalence relation among them.

Equivalence Schedules
An equivalence schedule can be of the following types −

Result Equivalence

If two schedules produce the same result after execution, they are said to be result
equivalent. They may yield the same result for some value and different results for
another set of values. That's why this equivalence is not generally considered
significant.

View Equivalence

Two schedules would be view equivalence if the transactions in both the schedules
perform similar actions in a similar manner.
For example −
 If T reads the initial data in S1, then it also reads the initial data in S2.
 If T reads the value written by J in S1, then it also reads the value written by J
in S2.
 If T performs the final write on the data value in S1, then it also performs the
final write on the data value in S2.

Conflict Equivalence

Two schedules would be conflicting if they have the following properties −

 Both belong to separate transactions.


 Both accesses the same data item.
 At least one of them is "write" operation.
Two schedules having multiple transactions with conflicting operations are said to
be conflict equivalent if and only if −

 Both the schedules contain the same set of Transactions.


 The order of conflicting pairs of operation is maintained in both the schedules.
Note − View equivalent schedules are view serializable and conflict equivalent
schedules are conflict serializable. All conflict serializable schedules are view
serializable too.

States of Transactions
A transaction in a database can be in one of the following states −

 Active − In this state, the transaction is being executed. This is the initial
state of every transaction.
 Partially Committed − When a transaction executes its final operation, it is
said to be in a partially committed state.
 Failed − A transaction is said to be in a failed state if any of the checks made
by the database recovery system fails. A failed transaction can no longer
proceed further.
 Aborted − If any of the checks fails and the transaction has reached a failed
state, then the recovery manager rolls back all its write operations on the
database to bring the database back to its original state where it was prior to
the execution of the transaction. Transactions in this state are called aborted.
The database recovery module can select one of the two operations after a
transaction aborts −
o Re-start the transaction
o Kill the transaction
 Committed − If a transaction executes all its operations successfully, it is
said to be committed. All its effects are now permanently established on the
database system.
Deadlocks Deadlock is a situation where transaction have acquired data and
waiting for others to release data to acquire further data and as a result none will
release acquired data and will get required data and will lead to infinite wait for
the transactions, and it is referred as deadlock.
Deadlock is a situation which we don’t want to occur and if a system is
implemented in strict serial order then it is guaranteed that deadlock will not
occur but this approach will slow down the overall system performance as the
resources will be underutilized and so to optimize the system performance we
let the deadlock to occur and whenever it occurs, system concept of mutual
understanding and some transaction will roll back and then other transaction
can complete and release the resources so that other transactions will also
execute. The strongest condition for deadlock to occur is circular wait which is
illustrated as follows if t1 & t2 are two transactions and r1, r2 are two resources
T1
R1 R2
T2
The above situation represents circular wait where T1 is requesting for R1 and it
is already taken by T2 and T2 is also requesting R1 and it is already taken by T1
and T1 & T2 both have acquired one resource and waiting for each other to
release other one and neither T1 nor T2 will proceed and leading to deadlock.
In a multiprogramming environment where multiple transactions can be executed
simultaneously, it is highly important to control the concurrency of transactions. We
have concurrency control protocols to ensure atomicity, isolation, and serializability of
concurrent transactions. Concurrency control protocols can be broadly divided into two
categories −

 Lock based protocols


 Time stamp based protocols

Lock-based Protocols
Database systems equipped with lock-based protocols use a mechanism by which any
transaction cannot read or write data until it acquires an appropriate lock on it. Locks
are of two kinds −
 Binary Locks − A lock on a data item can be in two states; it is either locked or
unlocked.
 Shared/exclusive − This type of locking mechanism differentiates the locks
based on their uses. If a lock is acquired on a data item to perform a write
operation, it is an exclusive lock. Allowing more than one transaction to write on
the same data item would lead the database into an inconsistent state. Read
locks are shared because no data value is being changed.
There are four types of lock protocols available −
Simplistic Lock Protocol
Simplistic lock-based protocols allow transactions to obtain a lock on every object
before a 'write' operation is performed. Transactions may unlock the data item after
completing the ‘write’ operation, this technique happens to be very simple to implement
but will lead to various types constancy problems such as the data can be released
even if transaction is under progress and hence leading to read of intermediate values
of the data and hence leading to isolation not getting satisfied. And hence such
techniques are not used.
Pre-claiming Lock Protocol
Pre-claiming protocols evaluate their operations and create a list of data items on
which they need locks. Before initiating an execution, the transaction requests the
system for all the locks it needs beforehand. If all the locks are granted, the transaction
executes and releases all the locks when all its operations are over. If all the locks are
not granted, the transaction rolls back and waits until all the locks are granted.

This technique also is not used as it under utilizes the resources so slowing down the overall
performance but it will guarantee deadlock free states.

Two-Phase Locking 2PL


This locking protocol divides the execution phase of a transaction into three parts. In
the first part, when the transaction starts executing, it seeks permission for the locks it
requires. The second part is where the transaction acquires all the locks. As soon as
the transaction releases its first lock, the third phase starts. In this phase, the
transaction cannot demand any new locks; it only releases the acquired locks.
Two-phase locking has two phases, one is growing, where all the locks are being
acquired by the transaction; and the second phase is shrinking, where the locks held
by the transaction are being released.
To claim an exclusive (write) lock, a transaction must first acquire a shared (read) lock
and then upgrade it to an exclusive lock.
Strict Two-Phase Locking
The first phase of Strict-2PL is same as 2PL. After acquiring all the locks in the first
phase, the transaction continues to execute normally. But in contrast to 2PL, Strict-2PL
does not release a lock after using it. Strict-2PL holds all the locks until the commit
point and releases all the locks at a time.

Strict-2PL does not have cascading abort as 2PL does.

Timestamp-based Protocols
The most commonly used concurrency protocol is the timestamp based protocol. This
protocol uses either system time or logical counter as a timestamp.
Lock-based protocols manage the order between the conflicting pairs among
transactions at the time of execution, whereas timestamp-based protocols start working
as soon as a transaction is created.
Every transaction has a timestamp associated with it, and the ordering is determined
by the age of the transaction. A transaction created at 0002 clock time would be older
than all other transactions that come after it. For example, any transaction 'y' entering
the system at 0004 is two seconds younger and the priority would be given to the older
one.
In addition, every data item is given the latest read and write-timestamp. This lets the
system know when the last ‘read and write’ operation was performed on the data item.

Timestamp Ordering Protocol


The timestamp-ordering protocol ensures serializability among transactions in their
conflicting read and write operations. This is the responsibility of the protocol system
that the conflicting pair of tasks should be executed according to the timestamp values
of the transactions.

 The timestamp of transaction T  is denoted as TS(T ).


i i

 Read time-stamp of data-item X is denoted by R-timestamp(X).


 Write time-stamp of data-item X is denoted by W-timestamp(X).
Timestamp ordering protocol works as follows −
 If a transaction Ti issues a read(X) operation −
o If TS(Ti) < W-timestamp(X)
 Operation rejected.
o If TS(Ti) >= W-timestamp(X)
 Operation executed.
o All data-item timestamps updated.
 If a transaction Ti issues a write(X) operation −
o If TS(Ti) < R-timestamp(X)
 Operation rejected.
o If TS(Ti) < W-timestamp(X)
 Operation rejected and Ti rolled back.
o Otherwise, operation executed.

Pract1 Create table mentioned in notes. Also use alter table to add constraints.

create table products(


mfrid number(4),
prid number(4),
name varchar2(30),
price number(10,5),
qtyav integer,
constraint pk1 primary key(mfrid,prid));

create table customer(


custid number(4) primary key,
name varchar2(30),
rep number(4),
city varchar2(30),
creditlimit number(15,5),
region varchar2(20));

create table salesreps(


empid number(4) primary key,
name varchar2(30),
joindate date,
repoff number(4),
mgr number(4),
sales number(20,10),
target number(20,10),
constraint fk1 foreign key(mgr) references salesreps);
create table orders(
ordid number(4) primary key,
o_date date,
cust number(4),
rep number(4),
mfrid number(4),
prid number(4),
amt number(12,5),
qty integer,
constraint fk2 foreign key(mfrid,prid) references products,
constraint fk3 foreign key(cust) references customer,
constraint fk4 foreign key(rep) references salesreps);

create table office(


offid number(4) primary key,
manager number(4),
city varchar2(30),
region varchar2(20),
sales number(20,10),
target number(20,10),
constraint fk5 foreign key(manager) references salesreps);

Alter table customer


add constraint fk6 foreign key(rep) references salesreps;

Alter table salesreps


add constraint fk7 foreign key(repoff) references office;
Pract2 Insert 5 rows in salesreps table, 10 rows in customer table, 5 rows in office
table, 15 rows in orders table & 5 rows in products table.

Pract3:
q.1 List all office’s details
select *
from Office;
q.2 List employees with their name id and sales.
Select empid, name, sales
From salesreps;
q.3 List orders details
select *
from orders;
q.4 List orders accepted in last quarter of 2015
select *
from orders
where date >= ’01-oct-2015’ and date <=’31-dec-2015’;
q.5 List products details with quantity available for more than 25
select *
from products
where qtyav > 25;
q.6 List all customer’s detail
select *
from customer;
q.7 List offices with id, region and sales in eastern region;
select oid, region, sales
from offices
where region = ‘esatern’;
q.8 List employees with id name sales target if sales is below 50%;
select empid, name, sales, target
from salesreps
where sales < 0.5*target;

Pract4
q.1 List products with quantity on hand if price is more rs.100 sorted in descending order of
product name.
select mfrid,prid,name,qtyav
from products
where price>100
order by name desc;
q.2 List customers with their name city and region if customer is residing in city Mumbai or
thane sorted in alphbetical order of city name.
select custid, name, city, region
from customers
where city = ‘Mumbai’
or city = ‘Thane’
order by city;
q.3 List average amount of orders accepted in 2 nd half of year 2018 and order is for a product
with mfrid as 1001 and product id as 2001.
Select avg(amt)
From orders
Where date>= ’01-jun-2018’
And date <= ’31-dec-2018’
And Mfrid = 1001
And prid = 2001;
q.4 List total no of orders accepted in the 2019.
Select count(*)
From orders
Where extract (year from date) = 2019;
q.5 List total no of employees joined in year 2017 or 2016.
Select count(*)
From salesreps
Where extract (year from date) = 2016
Or extract (year from date) = 2017
q.6 List total no of sales values and total employees.
Select count(sales), count count(*)
From salesreps;
q.7 List employees with their name, sales, target and joindate grouped according their date of
join.
Select empid, name, sales, target, joindate
From salesreps
Group by joindate, empid, name, sales, target;
q.8 List product details grouped according to their quantity available
select mfrid, prid, name, proice, qtyav
from products
group by qtyav, mfrid, prid, name, proice
q.9 List orders with orderid date amount grouped according to their order date.
Select ordid, date, amt
From orders
Group by date, ordid,amt;
Pract5
Q.1 List employees with their name sales target and date of join for employees whose name
starts with a character A.
Select empid, name, sales, target, joindate
From salesreps
Where name like ‘A%’;
Q.2 List employees with their name sales target and joindate if employee’s name is starting
with 3 character as d and ending with 3rd last character as j and is above performance by 10%
rd

and has joined in month of January or April or October.


Select empid, name, sales, target, joindate
From salesreps
Where name like ‘_ _ d%j_ _’
And sales > target*1.1
And extract (month from joindate) = ‘Jan’
Or extract (month from joindate) = ‘apr’
Or extract (month from joindate) = ‘oct’;
Q.3 List employees with their name date of join age and the amount by which sales is above
or below the target for employees with dob before 1990 and name has 2 nd character as b 2nd last
character as h and last character as *.
Select empid, name, joindate, (sysdate-dob) as age, (sales – target)
From salesreps
Where dob < ’01-jan-1990’
And name like ‘-b%h$*’ escape ‘$’;
Q.4 List employees with their id, name and target along with customer with id name and
credit limit if credit limit is more than 50000 and customer is assigned to an employee with name
starting with first character as D and ending with j.
Select empid, salesreps.name, target, custid, customer.name, creditlimit
From salesreps, customers
Where custrep = empid
And creditlimit > 50000
Salesreps.name like ‘D%j’;
Q.5 List orders with id date amount along with products with name and price if inventory
value of product is more that 100000 and order has been accepted by an employee with sales
more than target and employee is working in office with sales below target.
Select ordid, date, amt, products.name, price
From orders, products, salesreps, office
Where orders.prid = products.prid
And orders.mfrid = products.mfrid
And price*qtyav > 100000
And salesreps.sales > salesreps.target
Office.sales < office.target;
Q.6 List employees with their order details grouped according to employee.
Select empid, name, ordid, date, amt
From orders, salesreps
Where rep = empid
Group by empid, name, ordid, date,amt;
Q.7 List office details with employees working under those offices if employees have
accepted a minimum of 20 orders and total amount of100000.
Select offid, region,city, empid, name
From office, salesreps, orders
Where repoff = offid
Rep = empid
Group by empid, name, offid,region, city
Having count(*) >= 20
And sum(amt) = 100000;

Pract6
Q.1 List products with inventory values if product name starts with 2nd character as b and ends
with 3rd last character as c and has an average order amount of at least 10000 and order
has been accepted by an employee joined in 1st half of 2015.
Select p.mfrid, p.prid, p.name, price*qtyav
From products p, orders o, salesreps s
Where o.mfrid = p.mfrid
And o.prid = p.prid
And rep = empid
And p.name like ‘_b%c__’
And joindate between ‘1-jan-2015’ and ‘3-jun-2015’
Group by p.mfrid, p.prid, p.name, price*qtyav
Having avg(amt) >=10000;
Q.2 List employees with their id and name having sales less than average sales of all
employees.(use sub query)
Select empid, name
From salesreps
Where sales < ( Select avg(sales)
From salesreps);
Q.3 List employees if their sales is less than their total order amount.(use sub query)
Select empid, name, sales
From salesreps
Where sales < ( select sum(amt)
From orders
Where rep = empid);
Q.4 List order details if order amount is more than sales of an employee.(use sub query)
Select ordid, date, amt
From orders
Where amt > any (select sales
From salesrpes);
Q.5 List employee detail if they accepted any order of amount for more than 500.(use sub
query)
Select empid, name, joindate, sales
From salesreps
Where empid in (select rep
From orders
Where amt > 500);
Q.6 List the offices where there is a salesperson whose target represents more than 55
percent of the office’s target.(use sub query)
Select offid, region, city
From offices
Where exists (select *
From Salesreps
Where repoff = offid
And target > (0.55*offices.target));

Q.7 Create a view called bigorders for the orders with amount more than 50000
Create view bigorders as
Select *
From orders
Where amt > 50000;

Pract7
Q.1 Write a block to read 2 integers from user and print their addition.
Q.2 Write a block to read an integer between 1 and 10 and display it in word format. If no is
not in the range then display that no is out of range.
Q.3 Write a block print all even nos from 1 to 100.
Q.4 Write a program to select the detail of employee no 101 and print the name, date of join
sales & target of that employee.
Q.5 Write a program to read in integer from user and use case statement to print no in words
if it is within 1 to 10 otherwise print no out of range.
Q.6 Write a program to illustrate use of NO_DATA_FOUND & TO_MANY_ROWS
exceptions.
Pract8
Q.1 Write a program to increase target of employees of 25% if their sales is more than target.
Also print the total no of rows updated if there is any employee satisfying the condition.
Q.2 Write a program to create a cursor with all employees with sales more than target and use
this cursor to print the name, sales and target of employee.
Q.3 Write a program to create a cursor for employees with their id, name, date of join, sales,
target and their order id, order date and amount print the name of employee if there is any
having their order amount more than their target.
Q.4 Write a block to call a procedure with parameter as eid and find out the name sales &
target of employee and print the output.
Q.5 Write a block to call a function with parameter as eid and find out the total order amount
and return it to the block again to display output.

PRACT 3: SYNTAX1
INSERT INTO TABLENAME(COLNAME1,COLNAME2,......,COLNAMEN)
VALUES(VALUE1, VALUE2,..........,VALUEN);
Use above syntax to insert 15 rows in orders table, 5 rows in salesreps table, 5 rows in customer
table 5 rows in office table and 5 rows in products table
Ist insert into products table then in customer table then in salesreps table the in office table and
last in orders table.
Login as system user with user id as system and password probably u all must have taken oracle
Then write the query as
Select * from user_tab; so u will see all users and then accordingly u can find out the user names

CE – II
Assignment 1:
Q.1 Draw an ER Diagram for college management system where system will include
different courses with students, teachers classrooms timetable along with admission of
students in courses.
Q.2 Convert above ER diagram in tables and apply normalization rules.

Assignments2:
Q.1 Explain selection, projection, combination of selection and projection along with
Cartesian product with examples.
Q.2 Explain 1 NF and 3 NF with one - one example.

Assignment3:
Q.1 Write any 15 queries using the tables created in assignment 1.
q.2 Write any 10 relational expressions using the relations from assignment 1.
Assignments4:
Q.1 Explain unnamed blocks and illustrate it with either if or any type of loop statement.
Q.2 Explain Cursors and illustrate either implicit cursor or explicit cursor with any one type
of in built attribute.
Assignment5:
Q.1 Explain database control statements.
Q.2 Explain database transactions.

You might also like