Sie sind auf Seite 1von 86

Experiment 1

Date:

Objective:
Introduction to SQL. Also design SQL tables for Client Master & Product Master database
and display all the values.

Software Used:
Oracle 12c & DataGrip IDE

Q1. Create the following tables:

i) Client_master
columnname datatype size
client_no varchar2 6
name varchar2 20
address1 varchar2 30
address2 varchar2 30
city varchar2 15
state varchar2 15
pincode number 6
bal_due number 10,2

ii) Product_master
Columnname datatype size
Product_no varchar2
Description varchar2
Profit_percent number
Unit_measure varchar2
Qty_on_hand number
Reoder_lvl number
Sell_price number
Cost_price number

Q2. Insert the following data into their respective tables:

Client_no Name city pincode state bal.due

0001 Ivan Bombay 400054 Maharashtra 15000


0002 Vandana Madras 780001 Tamilnadu 0
0003 Pramada Bombay 400057 Maharashtra 5000
0004 Basu Bombay 400056 Maharashtra 0
0005 Ravi Delhi 100001 2000
0006 Rukmini Bombay 400050 Maharashtra 0
Data for Product Master:

Product No. Description Profit % Unit Qty Reorder Sell Cost


Percent measured on hand lvl price price

P00001 1.44floppies 5 piece 100 20 525 500


P03453 Monitors 6 piece 10 3 12000 11200
P06734 Mouse 5 piece 20 5 1050 500
P07865 1.22 floppies 5 piece 100 20 525 500
P07868 Keyboards 2 piece 10 3 3150 3050
P07885 CD Drive 2.5 piece 10 3 5250 5100
P07965 540 HDD 4 piece 10 3 8400 8000
P07975 1.44 Drive 5 piece 10 3 1050 1000
P08865 1.22 Drive 5 piece 2 3 1050 1000

Q3:- On the basis of above two tables answer the following Questionnaires:

i) Find out the names of all the clients.


ii) Retrieve the list of names and cities of all the clients.
iii) List the various products available from the product_master table.
iv) List all the clients who are located in Bombay.
v) Display the information for client no 0001 and 0002.
vi) Find the products with description as ‘1.44 drive’ and ‘1.22 Drive’.
vii) Find all the products whose sell price is greater than 5000.
viii) Find the list of all clients who stay in in city ‘Bombay’ or city ‘Delhi’ or ‘Madras’.
ix) Find the product whose selling price is greater than 2000 and less than or equal to 5000.
x) List the name, city and state of clients not in the state of ‘Maharashtra’.

Theory & Concepts:

Introduction about SQL-


SQL (Structured Query Language) is a non-procedural language, you specify what you want, not how
to get it. A block structured format of English key words is used in this Query language. It has the
following components.

DDL (Data Definition Language)-


The SQL DDL provides command for defining relation schemas, deleting relations and modifying
relation schema.

DML (DATA Manipulation Language)-


It includes commands to insert tuples into, delete tuples from and modify tuples in the database.

View definition-
The SQL DDL includes commands for defining views.
Transaction Control- SQL includes for specifying the beginning and ending of transactions.
Embedded SQL and Dynamic SQL-
Embedded and Dynamic SQL define how SQL statements can be embedded with in general purpose
programming languages, such as C, C++, JAVA, COBOL, Pascal and Fortran.

Integrity-
The SQL DDL includes commands for specifying integrity constraints that the data stored in the
database must specify. Updates that violate integrity constraints are allowed.

Authorization-
The SQL DDL includes commands for specifying access rights to relations and views.

Data Definition Language-

The SQL DDL allows specification of not only a set of relations but also information about each
relation, including-
 Schema for each relation
 The domain of values associated with each attribute.
 The integrity constraints.
 The set of indices to be maintained for each relation.
 The security and authorization information for each relation.
 The physical storage structure of each relation on disk.

Domain types in SQL-

The SQL standard supports a variety of built in domain types, including-


 Char (n)- A fixed length character length string with user specified length .
 Varchar (n)- A variable character length string with user specified maximum length n.
 Int- An integer.
 Small integer- A small integer.
 Numeric (p, d)-A Fixed point number with user defined precision.
 Real, double precision- Floating point and double precision floating point numbers with
machine dependent precision.
 Float (n)- A floating point number, with precision of at least n digits.
 Date- A calendar date containing a (four digit) year, month and day of the month.
 Time- The time of day, in hours, minutes and seconds Eg. Time ’09:30:00’.
 Number- Number is used to store numbers (fixed or floating point).

DDL statement for creating a table-

Syntax-
Create table tablename
(columnname datatype(size), columnname datatype(size));
Creating a table from a table-

Syntax-
CREATE TABLE TABLENAME
[(columnname, columnname, ………)]
AS SELECT columnname, columnname……..FROM tablename;
Insertion of data into tables-

Syntax-
INSERT INTO tablename
[(columnname, columnname, ………)]
Values(expression, expression);

Inserting data into a table from another table:

Syntax-
INSERT INTO tablename
SELECT columnname, columnname, …….
FROM tablename;

Insertion of selected data into a table from another table:

Syntax-
INSERT INTO tablename
SELECT columnname, columnname……..
FROM tablename
WHERE columnname= expression;

Retrieving of data from the tables-

Syntax-
SELECT * FROM tablename;

The retrieving of specific columns from a table-

Syntax-
SELECT columnname, columnname, ….
FROM tablename;

Elimination of duplicates from the select statement-

Syntax-
SELECT DISTINCT columnname, columnname
FROM tablename;

Selecting a data set from table data-


Syntax-
SELECT columnname, columnname
FROM tablename
WHERE searchcondition;

Output:

Ans 1. Creating tables i. client_master and ii. product_master.

Query:

i. create table client_master (client_no varchar2(6), name varchar2(30),


address1 varchar2(30), address2 varchar2(30), city varchar2(15),
state varchar2(15), pincode number(6), bal_due number(10,2));

ii. create table product_master (product_no varchar2(50), description varchar2(30),profit_percent


number(10,2), unit_measure varchar2(30), qty_on_hand number(15),reorder_lvlnumber number(15),
sell_price number(38,2), cost_price number(38,2));

Result:

i. ii.

Ans 2. Inserting values in i. client_master and ii. product_master.

Query:

i. insert into client_master (client_no, name,city, pincode, state, bal_due) values


('0001','Ivan','Bombay','400054','Maharashtra','15000');
insert into client_master (client_no,name,city,pincode,state,bal_due) values
('0002','Vandana','Madras','780001','Tamilnadu','0');
insert into client_master (client_no,name,city,pincode,state,bal_due) values
('0003','pramada','Bombay','400057','Maharashtra','5000');
insert into client_master (client_no,name,city,pincode,state,bal_due) values
('0004','Basu','Bombay','400056','Maharashtra','0');
insert into client_master (client_no,name,city,pincode,bal_due) values ('0005','Ravi','Delhi','100001','2000');
insert into client_master (client_no,name,city,pincode,state,bal_due) values
('0006','Rukmani','Bombay','400050','Maharashtra','0');

ii. insert into product_master (product_no, description,profit_percent,unit_measure,


qty_on_hand,reorder_lvlnumber,sell_price,cost_price) values
('p00001','1.44floppies','5','peice','100','20','525','500');
insert into product_master (product_no,description,profit_percent,unit_measure,
qty_on_hand,reorder_lvlnumber,sell_price,cost_price) values ('p00001','Monitors',
'6','peice','10','3','12000','11200');
insert into product_master (product_no,description,profit_percent,unit_measure,
qty_on_hand,reorder_lvlnumber,sell_price,cost_price) values ('p00001','Mouse','5','peice','20','5','1050','500');
insert into product_master (product_no,description,profit_percent,unit_measure,
qty_on_hand,reorder_lvlnumber,sell_price,cost_price) values
('p00001','1.22floppies','5','peice','100','20','525','500');
insert into product_master (product_no,description,profit_percent,unit_measure,
qty_on_hand,reorder_lvlnumber,sell_price,cost_price)
values ('p00001','Keyboard','2','peice','10','3','3150','3050');
insert into product_master (product_no,description,profit_percent,unit_measure,
qty_on_hand,reorder_lvlnumber,sell_price,cost_price)
values ('p00001','CD_drive','2.5','peice','10','3','5250','5100');
insert into product_master (product_no,description,profit_percent,unit_measure,
qty_on_hand,reorder_lvlnumber,sell_price,cost_price)
values ('p00001','540 HDD','4','peice','10','3','8400','8000');
insert into product_master (product_no,description,profit_percent,unit_measure,
qty_on_hand,reorder_lvlnumber,sell_price,cost_price)
values ('p00001','1.44Drive','5','peice','10','3','1050','1000');
insert into product_master (product_no,description,profit_percent,unit_measure,
qty_on_hand,reorder_lvlnumber,sell_price,cost_price)
values ('p00001','1.22Drive','5','peice','2','3','1050','1000');

Result:

i. client_master

ii. product_master
Ans 3.

i. Find out the names of all the clients.

Query: select name from client_master;

Result:

ii. Retrieve the list of names and cities of all the clients.

Query: select name,city from client_master;

Result :

iii. List the various products available from the product_master table.

Query: select description from product_master;

Result:
iv. List all the clients who are located in Bombay.

Query: select name from client_master where city='Bombay';

Result:

v. Display the information for client no 0001 and 0002.

Query: select * from client_master where client_no='0001' or client_no='0002';

Result:

vi. Find the products with description as ‘1.44 drive’ and ‘1.22 Drive’.

Query: select * from product_master where description='1.44Drive' or description='1.22Drive';

Result:

vii. Find all the products whose sell price is greater than 5000.

Query: select * from product_master where sell_price >'5000';

Result:
viii. Find the list of all clients who stay in in city ‘Bombay’ or city ‘Delhi’ or ‘Madras’.

Query: select * from client_master where city='Bombay' or city='Madras' or city='Delhi' ;

Result:

ix. Find the product whose selling price is greater than 2000 and less than or equal to 5000.

Query: select * from product_master where sell_price >2000 and sell_price <= 5000;

Result:

x. List the name, city and state of clients not in the state of ‘Maharashtra’.

Query: select name,city,state from client_master where state !='Maharashtra' or state is null;

Result:
Experiment 2

Date:

Objective:
Create the SQL queries for commands like update, alter, rename, delete and drop.

Software Used:
Oracle 12c & DataGrip IDE

Q1 Using the table client master and product master answer the following questionnaires.

i. Change the selling price of ‘1.44 floppy drive to Rs.1150.00


ii. Delete the record with client 0001 from the client master table.
iii. Change the city of client_no’0005’ to Bombay.
iv. Change the bal_due of client_no ‘0001, to 1000.
v. Find the products whose selling price is more than 1500 and also find the new selling price as
original selling price *15.
vi. Find out the clients who stay in a city whose second letter is a.
vii. Find out the name of all clients having ‘a’ as the second letter in their names.
viii. List the products in sorted order of their description.
ix. Count the total number of orders
x. Calculate the average price of all the products.
xi. Calculate the minimum price of products.
xii. Determine the maximum and minimum prices . Rename the tittle as ‘max_price’ and
min_price respectively.
xiii. Count the number of products having price greater than or equal to 1500.

Theory & Concepts:

DML ( Data Manipulation Language) Data manipulation is

 The retrieval of information stored in the database.


 The insertion of new information into the database.
 The deletion of information from the database.
 The modification of information stored by the appropriate data model. There are basically two
types.
(i) Procedural DML:- require a user to specify what data are needed and how to get those
data.
(ii) Non Procedural DML : require a user to specify what data are needed without specifying
how to get those data.

Updating the content of a table:


In creation situation we may wish to change a value in table without changing all values in the tuple .
For this purpose the update statement can be used.

Update table name


Set columnname = experision, columnname =expression……
Where columnname = expression;

Deletion Operation:-
A delete reQuestionst is expressed in much the same way as Questionry. We can delete whole tuple
( rows) we can delete values on only particulars attributes.

Deletion of all rows

Syntax:
Delete from tablename :

Deletion of specified number of rows


Syntax:

Delete from table name


Where search condition ;

Computation in expression lists used to select data

+ Addition - Subtraction
* multiplication ** exponentiation
/ Division () Enclosed operation

Renaming columns used with Expression Lists: - The default output column names can be renamed
by the user if required

Syntax:

Select column name result_columnname,


Columnname result_columnname,
From table name;

Logical Operators:
The logical operators that can be used in SQL sentenced are
AND all of must be included
OR any of may be included
NOT none of could be included

Range Searching: Between operation is used for range searching.

Pattern Searching:
The most commonly used operation on string is pattern matching using the operation ‘like’ we
describe patterns by using two special characters.

 Percent (%) ; the % character matches any substring we consider the following examples.
 ‘Perry %’ matches any string beginning with perry
 ‘% idge % matches any string containing’ idge as substring.
 ‘ - - - ‘ matches any string exactly three characters.
 ‘ - - - % matches any string of at least of three characters.

Oracle functions:
Functions are used to manipulate data items and return result. function follow the format of function
_name (argument1, argument2 ..) .An arrangement is user defined variable or constant. The structure
of function is such that it accepts zero or more arguments.
Examples:
Avg return average value of n

Syntax:
Avg ([distinct/all]n)
Min return minimum value of expr.

Syntax:
MIN((distict/all )expr)
Count Returns the no of rows where expr is not null
Syntax:
Count ([distinct/all)expr]
Count (*) Returns the no rows in the table, including duplicates and those with nulls.
Max Return max value of expr

Syntax:

Max ([distinct/all]expr)
Sum Returns sum of values of n

Syntax:
Sum ([distinct/all]n)
Sorting of data in table

Syntax:
Select columnname, columnname
From table
Order by columnname;

Output:

i. Change the selling price of ‘1.44 floppy drive to Rs.1150.00

Query: update product_master set sell_price=1150.00 where description='1.44floppies';

Result:

ii. Change the city of client_no’0005’ to Bombay.

Query: update client_master set city='Bombay' where client_no='0005';

Result:

iii. Change the bal_due of client_no ‘0001, to 1000.

Query: update client_master set bal_due=1000 where client_no='0001';

Result:

iv. Find the products whose selling price is more than 1500 and also find the new
selling price as original selling price *15.
Query: select description from product_master where sell_price > 1500;
update product_master set sell_price=sell_price*15;
select sell_price from product_master;

Result:

v. Find out the clients who stay in a city whose second letter is a.

Query: select * from CLIENT_MASTER where city like '_a%';

Result:

vi. Find out the name of all clients having ‘a’ as the second letter in their names.

Query: select name from CLIENT_MASTER where name like '_a%';

Result:

vii. List the products in sorted order of their description.

Query: select * from product_master order by description asc;

Result:
viii. Count the total number of orders

Query: select sum (reorder_lvlnumber) from product_master;

Result:

ix. Calculate the average price of all the products.

Query: select avg (cost_price) from product_master;

Result:

x. Calculate the minimum price of products.

Query: select min (cost_price) from product_master;

Result:

xi. Determine the maximum and minimum prices . Rename the tittle as ‘max_price’ and
min_price respectively.

Query: select min (cost_price) as min_price,


max (cost_price) as max_price from product_master;

Result:

xii. Count the number of products having price greater than or equal to 1500.

Query: select count (cost_price) from product_master where cost_price >= 1500;

Result:
xiii. Delete the record with client 0001 from the client master table.

Query: delete * from client_master where client_no='0001';

Result:
Experiment 3
Date:

Objective:
To Implement the restrictions on the table.

Software Used:
Oracle 12c & DataGrip IDE

Question1 : Create the following tables:

i. Sales_master

Columnname Datatype Size Attributes


Salesman_no varchar2 6 Primary key/first letter
must start with ‘s’
Sal_name varchar2 20 Not null
Address varchar2 Not null
City varchar2 20
State varchar2 20
Pincode Number 6
Sal_amt Number 8,2 Not null, cannot be 0
Tgt_to_get Number 6,2 Not null, cannot be 0
Ytd_sales Number 6,2 Not null, cannot be 0
Remarks Varchar2 30

ii. Sales_order

Columnname Datatype Size Attributes


S_order_no varchar2 6 Primary/first letter must be 0
S_order_date Date 6 Primary key reference clientno
of client_master table
Client_no Varchar2 25
Dely_add Varchar2 6
Salesman_no Varchar2 6 Foreign key references
salesman_no of
salesman_master table
Dely_type Char 1 Delivery part(p)/full(f),default f
Billed_yn Char 1
Dely_date Date Can not be lessthan
s_order_date
Order_status Varchar2 10 Values (‘in
process’;’fulfilled’;back
order’;’canceled

iii. Sales_order_details

Column Datatype Size Attributes

S_order_no Varchar2 6 Primary key/foreign


key references
s_order_no of
sales_order
Product_no Varchar2 6 Primary key/foreign
key references
product_no of
product_master
Qty_order Number 8
Qty_disp Number 8
Product_rate Number 10,2

Insert the following data into their respective tables using insert statement:

i. Data for sales_man master table


Salesma Salesman Addre City Pin State Sala Tgt_to_g Ytd Remar
n_no name ss code mt et Sales k
500001 Kiran A/14 Bo 40000 Mah 3000 100 50 Good
worli mb 2
ay
500002 Manish 65,nari Bo 40000 Mah 3000 200 100 Good
man mb 1
ay
500003 Ravi P-7 Bo 40003 Mah 3000 200 100 Good
Bandr mb 2
a ay
500004 Ashish A/5 Bo 40004 Mah 3500 200 150 Good
Juhu mb 4
ay

ii. Data for salesorder table:


S_orderno S_orderdate Client no Dely Bill Salesman Delay Order
type yn no date status
019001 12-jan-96 0001 F N 50001 20-jan- Ip
96
019002 25-jan-96 0002 P N 50002 27-jan- C
96
016865 18-feb-96 0003 F Y 500003 20-feb- F
96
019003 03-apr-96 0001 F Y 500001 07-apr- F
96
046866 20-may-96 0004 P N 500002 22- C
may-96
010008 24-may-96 0005 F N 500004 26- Ip
may-96

iii. Data for sales_order_details table:

S_order no Product no Qty ordered Qty disp Product_rate


019001 P00001 4 4 525
019001 P07965 2 1 8400
019001 P07885 2 1 5250
019002 P00001 10 0 525
046865 P07868 3 3 3150
046865 P07885 10 10 5250
019003 P00001 4 4 1050
019003 P03453 2 2 1050
046866 P06734 1 1 12000
046866 P07965 1 0 8400
010008 P07975 1 0 1050
010008 P00001 10 5 525

Theory & Concepts:

Data constraints: Besides the cell name, cell length and cell data type there are other
parameters i.e. other data constrains that can be passed to the DBA at check creation time.
The constraints can either be placed at column level or at the table level.

i. Column Level Constraints: If the constraints are defined along with the column
definition, it is called a column level constraint.
ii. Table Level Constraints: If the data constraint attached to a specify cell in a table
reference the contents of another cell in the table then the user will have to use table
level constraints.

Null Value Concepts:- while creating tables if a row locks a data value for particular
column that value is said to be null . Column of any data types may contain null values
unless the column was defined as not null when the table was created

Syntax:
Create table tablename
(columnname data type (size) not null ……)
Primary Key: primary key is one or more columns is a table used to uniquickly identity
each row in the table. Primary key values must not be null and must be uniQuestion
across the column. A multicolumn primary key is called composite primary key.

Syntax: primary key as a column constraint


Create table tablename
(columnname datatype (size) primary key,….)
Primary key as a table constraint
Create table tablename
(columnname datatype (size), columnname datatype( size)…
Primary key (columnname,columnname));

UniQuestion key concept:-A uniQuestion is similar to a primary key except that the
purpose of a uniQuestion key is to ensure that information in the column for each
record is uniQuestion as with telephone or devices license numbers. A table may have
many uniQuestion keys.

Syntax: UniQuestion as a column constraint.


Create table table name
(columnname datatype (size) uniQuestion);
UniQuestion as table constraint:
Create table tablename
(columnname datatype (size),columnname datatype (size)…uniQuestion
(columnname,columnname));

Default value concept: At the line of cell creation a default value can be assigned to
it. When the user is loading a record with values and leaves this cell empty, the DBA
wil automatically load this cell with the default value specified. The data type of the
default value should match the data type of the column

Syntax:
Create table tablename
(columnname datatype (size) default value,….);

Foreign Key Concept : Foreign key represents relationship between tables. A foreign
key is column whose values are derived from the primary key of the same of some
other table . the existence of foreign key implies that the table with foreign key is
related to the primary key table from which the foreign key is derived .A foreign key
must have corresponding primary key value in the primary key table to have meaning.
Foreign key as a column constraint

Syntax :
Create table table name
(columnname datatype (size) references another table name);

Foreign key as a table constraint:


Syntax :
Create table name
(columnname datatype (size)….
primary key (columnname);
foreign key (columnname)references table name);

Check Integrity Constraints: Use the check constraints when you need to enforce
intergrity rules that can be evaluated based on a logical expression following are a few
examples of appropriate check constraints.
 A check constraints name column of the coient_master so that the name is
entered in upper case.
 A check constraint on the client_no column of the client _master so that no
client_no value starts with ‘c’

Syntax:
Create table tablename
(columnname datatype (size) CONSTRAINT constraintname)
Check (expression));

Output:

Ans1.

i. Create sales_master table.

Query:

create table sales_master (


salesman_no varchar(6) not null primary key check(salesman_no like 's%'),
sal_name varchar2(20) not null,
address varchar2(20) not null,
city varchar2(20),
state varchar2(20),
pincode number(6),
sal_amt number(8,2) not null check(sal_amt>0),
tgt_to_get number(6,2) not null check(tgt_to_get>0),
ytd_sales number(6,2) not null check(ytd_sales>0),
remarks varchar2(30));

Result:
ii. Create sales order table.

Query:

create table sales_order (


s_order_no varchar(6) not null primary key check(s_order_no like '0%'),
s_order_date date not null,
client_no varchar2(25),
dely_add varchar2(6),
salesman_no varchar2(6),
dely_type char(1) default 'f',
billed_yn char(1),
dely_date date ,
order_status varchar2(10),
check (order_status in ('in process','fulfilled','back_order','cancelled')),
check (dely_type in ('p','f')),
check(dely_date>s_order_date),
constraint fk_salesman_no foreign key (salesman_no) references sales_master(salesman_no));

Result:

iii. Create sales_order_details table.

Query:

create table sales_order_details


(
s_order_no varchar2(6) not null,
product_no varchar2(6) not null,
qty_order number,
qty_display number,
product_rate number(10,2),
constraint pk_sod primary key (s_order_no,product_no),
constraint fk_s_o_n foreign key (s_order_no) references sales_order(s_order_no),
constraint fk_P_n foreign key (product_no) references product_master(product_no));

Result:
iv. Insert data into sales_master table.

Query:

insert into sales_master salesman_no,sal_name,address,city,state,pincode,


sal_amt,tgt_to_get,ytd_sales,remarks)values('s00001','Kiran','a/14 worli',
'Bombay','Maharashtra','400002','3000','100','50','good');
insert into sales_master (salesman_no,sal_name,address,city,state,pincode,
sal_amt,tgt_to_get,ytd_sales,remarks)values ('s00002','Manish','65 nariman',
'Bombay','Maharashtra','400001','3000','200','100','good');
insert into sales_master (salesman_no,sal_name,address,city,state,pincode,
sal_amt,tgt_to_get,ytd_sales,remarks)values ('s00003','Ravi','p-7 bandra',
'Bombay','Maharashtra','400032','3000','200','100','good');
insert into sales_master (salesman_no,sal_name,address,city,state,pincode,
sal_amt,tgt_to_get,ytd_sales,remarks)values ('s00004','Ashish','a/5 juhu'
,'Bombay','Maharashtra','400044','3500','200','150','good');

Result:

v. Insert data into sales_order table.

Query:

insert into sales_order(s_order_no,s_order_date,client_no,dely_type,


billed_yn,salesman_no,dely_date,order_status)values ('019001','12-jan-96',
'0001','f','n','s00001','20-jan-96','in process');
insert into sales_order(s_order_no,s_order_date,client_no,dely_type,
billed_yn,salesman_no,dely_date,order_status)values ('019002','25-jan-96',
'0002','p','n','s00002','27-jan-96','cancelled');
insert into sales_order(s_order_no,s_order_date,client_no,dely_type,
billed_yn,salesman_no,dely_date,order_status)values ('016865','18-feb-96',
'0003','f','y','s00003','20-feb-96','fulfilled');
insert into sales_order(s_order_no,s_order_date,client_no,dely_type,
billed_yn,salesman_no,dely_date,order_status)values ('019003','03-apr-96',
'0004','f','y','s00001','7-apr-96','fulfilled');
insert into sales_order(s_order_no,s_order_date,client_no,dely_type,
billed_yn,salesman_no,dely_date,order_status)values ('046866','20-may-96',
'0005','p','n','s00002','22-may-96','cancelled');
insert into sales_order(s_order_no,s_order_date,client_no,dely_type,
billed_yn,salesman_no,dely_date,order_status)values ('010008','24-may-96',
'0006','f','n','s00004','26-may-96','in process');

Result:

vi. Insert data into sales_order_details table.

Query:

insert into sales_order_details(s_order_no,product_no,qty_order,


qty_display,product_rate)values ('019001','p00001','4','4','525');
insert into sales_order_details(s_order_no,product_no,qty_order,
qty_display,product_rate)values ('019001','P07965','2','1','8400');
insert into sales_order_details(s_order_no,product_no,qty_order,
qty_display,product_rate)values ('019001','P07885','2','1','5250');
insert into sales_order_details(s_order_no,product_no,qty_order,
qty_display,product_rate)values ('019002','p00001','10','0','525');
insert into sales_order_details(s_order_no,product_no,qty_order,
qty_display,product_rate)values ('046865','P07868','3','3','3150');
insert into sales_order_details(s_order_no,product_no,qty_order,
qty_display,product_rate)values ('046865','P07885','10','10','5250');
insert into sales_order_details(s_order_no,product_no,qty_order,
qty_display,product_rate)values ('019003','p00001','4','4','1050');
insert into sales_order_details(s_order_no,product_no,qty_order,
qty_display,product_rate)values ('019003','p03453','2','2','1050');
insert into sales_order_details(s_order_no,product_no,qty_order,
qty_display,product_rate)values ('046866','p06734','1','1','12000');
insert into sales_order_details(s_order_no,product_no,qty_order,
qty_display,product_rate)values ('046866','P07965','1','0','8400');
insert into sales_order_details(s_order_no,product_no,qty_order,
qty_display,product_rate)values ('010008','P07975','1','0','1050');
insert into sales_order_details(s_order_no,product_no,qty_order,
qty_display,product_rate)values ('010008','p00001','10','5','525');

Result:
Relationship b/w tables after references.
Experiment 4

Date:

Objective:
To Implement the structure of the table

Software Used:
Oracle 12c & DataGrip IDE

Question 1. Create the following tables:

Challan_Header
Column name data type size Attributes
Challan_no varchar2 6 Primary key
s_order_no varchar2 6 Foreign key references s_order_no of
sales_order table
challan_date date not null
billed_yn char 1 values (‘Y’,’N’). Default ‘N’

Challan_Details
Column name data type size Attributes
Challan_no varchar2 6 Primary key
Product_no varchar2 6 Foreign key references to product_master
Qty_disp number 4,2 not null

Q2. Insert the following values into the challan header and challan_details tables:

i. Challan No S_order No Challan Date Billed

CH9001 019001 12-DEC-95 Y


CH865 046865 12-NOV-95 Y
CH3965 010008 12-OCT-95 Y

ii. challan_details table

Challan No Product No Qty Disp


CH9001 P00001 4
CH9001 P07965 1
CH9001 P07885 1
CH6865 P07868 3
CH6865 P03453 4
CH6865 P00001 10
CH3965 P00001 5
CH3965 P07975 2
Q3.– Answer the following questionaries.

Q1. Make the primary key to client_no in client_master.


Q2. Add a new column phone_no in the client_master table.
Q3. Add the not null constraint in the product_master table with the columns description,
profit percent , sell price and cost price.
Q4. Change the size of client_no field in the client_master table.
Q5. Select product_no, description where profit percent is between 20 and 30 both
inclusive.

Theory & Concepts:

Modifying the Structure of Tables- Alter table command is used to changing the structure
of a table. Using the alter table clause you cannot perform the following tasks:

(i) change the name of table


(ii) change the name of column
(iii) drop a column
(iv) decrease the size of a table if table data exists.

The following tasks you can perform through alter table command.

(i) Adding new columns:


Syntax
ALTER TABLE tablename
ADD (newcolumnname newdatatype (size));

(ii) Modifying existing table


Syntax:
ALTER TABLE tablename
MODIFY (newcolumnname newdatatype (size));

NOTE: Oracle not allow constraints defined using the alter table, if the data in the table,
violates such constraints.

Removing/Deleting Tables- Following command is used for removing or deleting a table.

Syntax:
DROP TABLE tabename:

Defining Integrity constraints in the ALTER TABLE command-

You can also define integrity constraints using the constraint clause in the ALTER TABLE
command. The following examples show the definitions of several integrity constraints.

(1) Add PRIMARY KEY-


Syntax:
ALTER TABLE tablename
ADD PRIMARY KEY(columnname);

(2) Add FOREIGN KEY-


Syntax:
ALTER TABLE tablename
ADD CONSTRAINT constraintname
FOREIGN KEY(columnname) REFERENCES tablename;

Dropping integrity constraints in the ALTER TABLE command:

You can drop an integrity constraint if the rule that if enforces is no longer true or if the
constraint is no longer needed. Drop the constraint using the ALTER TABLE command with
the DROP clause. The following examples illustrate the droping of integrity constraints.

(1) DROP the PRIMARY KEY-


Syntax:
ALTER TABLE tablename
DROP PRIMARY KEY

(2) DROP FOREIGN KEY-


Syntax:
ALTER TABLE tablename
DROP CONSTRAINT constraintname;

Output:

Ans 1

i. Create table challan_header

Query:

create table challan_header(


challan_no varchar2(6) not null primary key,
s_order_no varchar2(6),
challan_date date not null,
billed_yn char(1) default N ,
check(billed_yn in ('Y','N')),
constraint fk_so foreign key (s_order_no) references sales_order(s_order_no));
Result:

ii. Create table challan_details

Query:

create table challan_details(


challan_no varchar2(6) not null primary key check(challan_no like 'CH%'),
product_no varchar2(6) not null check(product_no like 'p%'),
qty_display number(4,2) not null,
constraint fk_pn foreign key (product_no) references product_master(product_no)
);

Result:

ANS 2

i. Insert data into challan_header table.

Query:

insert into challan_header (challan_no,s_order_no,challan_date,billed_yn)


values ('CH9001','019001','12-dec-95','Y');
insert into challan_header (challan_no,s_order_no,challan_date,billed_yn)
values ('CH865','046865','12-nov-95','Y');
insert into challan_header (challan_no,s_order_no,challan_date,billed_yn)
values ('CH3965','010008','12-oct-95','Y');

Result:
ii. Insert data into challan_details table.

Query:

insert into challan_details (challan_no,product_no,qty_display)


values ('CH9001','p00001',4);
insert into challan_details (challan_no,product_no,qty_display)
values ('CH9001','p07965',1);
insert into challan_details (challan_no,product_no,qty_display)
values ('CH9001','p07885',1);
insert into challan_details (challan_no,product_no,qty_display)
values ('CH6865','p07868',3);
insert into challan_details (challan_no,product_no,qty_display)
values ('CH6865','p03453',4);
insert into challan_details (challan_no,product_no,qty_display)
values ('CH6865','p00001',10);
insert into challan_details (challan_no,product_no,qty_display)
values ('CH3965','p00001',5);
insert into challan_details (challan_no,product_no,qty_display)
values ('CH3965','p07975',2);

Result:

Ans 3

i. Make the primary key to client_no in client_master.

Query:

alter table CLIENT_MASTER


modify client_no not null primary key ;
Result:

ii. Add a new column phone_no in the client_master table.

Query: :

alter table CLIENT_MASTER


add phone_no number(10);
Result

iii. Add the not null constraint in the product_master table with the columns description,
profit percent , sell price and cost price.

Query:

alter table PRODUCT_MASTER modify description not null;


alter table PRODUCT_MASTER modify profit_percent not null;
alter table PRODUCT_MASTER modify sell_price not null;
alter table PRODUCT_MASTER modify cost_price not null;

Result: (* attributes with circle in bottom right corner represents not null)
iv. Change the size of client_no field in the client_master table.

Query:

alter table CLIENT_MASTER modify CLIENT_NO varchar2(10);

Result:

v. Select product_no, description where profit percent is between 20 and 30 both inclusive.

Query:

select product_no,description from product_master where profit_percent


between 20 and 30;

Result:
Experiment 5
Date:

Objective:
To implement the concepts of joins.

Software Used:
Oracle 12c & DataGrip IDE

Theory:

Joint Multiple Table (Equi Join): Some times we require to treat more than one table as though
manipulate data from all the tables as though the tables were not separate object but one single
entity. To achieve this we have to join tables.Tables are joined on column that have dame data
type and data with in tables.

The tables that have to be joined are specified in the FROM clause and the joining
attributes in the WHERE clause.

Algorithm for JOIN in SQL:


1. Cartesian product of tables (specified in the FROM clause)
2. Selection of rows that match (predicate in the WHERE clause)
3. Project column specified in the SELECT clause.

1. CARTESIAN PRODUCT:-
Consider two table student and course
Select B.*,P.*
FROM student B, course P;

2. INNER JOIN:
Cartesian product followed by selection
Select B.*,P.*
FROM student B, Course P
WHERE B.course # P.course # ;

3. LEFT OUTER JOIN:


LEFT OUTER JOIN = Cartesian product + selection but include rows from the left table which are
unmatched pat nulls in the values of attributes belonging to th e second table
Exam:
Select B.*,P*
FROM student B left join course p
ON B.course # P.course #;

4. RIGHT OUTER JOIN:


RIGHT OUTER JOIN = Cartesian product + selection but include rows from right table which are
unmatched

Exam:
Select B.*,P.*
From student B RIGHT JOIN course P
B.course# = P course # ;

5. FULL OUTER JOIN


Exam
Select B.*,P.*
From student B FULL JOIN course P
On B.course # = P course # ;

Questionnaire’s:

1. Find out the product which has been sold to ‘Ivan Sayross.’
2. Find out the product and their quantities that will have do delivered.
3. Find the product_no and description of moving products.
4. Find out the names of clients who have purchased ‘CD DRIVE’
5. List the product_no and s_order_no of customers haaving qty ordered less than 5 from the order
details table for the product “1.44 floppies”.
6. Find the products and their quantities for the orders placed by ‘Vandan Saitwal ’ and “Ivan
Bayross”.
7. Find the products and their quantities for the orders placed by client_no “ C00001” and “C00002”
8. Find the order No,, Client No and salesman No. where a client has been received by more than
one salesman.
9. Display the s_order_date in the format “dd-mm-yy” e.g. “12- feb-96”
10. Find the date , 15 days after date.

Tables:

i. Product master
ii. Client master

iii. Sales order

iv. Sales order details

Output:

1. Find out the product which has been sold to ‘Ivan Sayross.’

Query:

SELECT PRODUCT_MASTER.DESCRIPTION
FROM PRODUCT_MASTER
INNER JOIN SALES_ORDER_DETAILS ON PRODUCT_MASTER.PRODUCT_NO =
SALES_ORDER_DETAILS.PRODUCT_NO
INNER JOIN SALES_ORDER ON SALES_ORDER_DETAILS.S_ORDER_NO = SALES_ORDER.S_ORDER_NO
INNER JOIN CLIENT_MASTER ON SALES_ORDER.CLIENT_NO = CLIENT_MASTER.CLIENT_NO WHERE
CLIENT_MASTER.NAME LIKE 'ivan';

2. Find out the product and their quantities that will have do delivered.

Query:

SELECT DISTINCT PRODUCT_MASTER.DESCRIPTION,SUM(SALES_ORDER_DETAILS.QTY_ORDER)


FROM PRODUCT_MASTER,SALES_ORDER_DETAILS
WHERE PRODUCT_MASTER.PRODUCT_NO = SALES_ORDER_DETAILS.PRODUCT_NO
GROUP BY PRODUCT_MASTER.DESCRIPTION;

3. Find the product_no and description of moving products.

Query:

SELECT DISTINCT PRODUCT_MASTER.DESCRIPTION,PRODUCT_MASTER.PRODUCT_NO


FROM PRODUCT_MASTER
INNER JOIN SALES_ORDER_DETAILS ON PRODUCT_MASTER.PRODUCT_NO =
SALES_ORDER_DETAILS.PRODUCT_NO
INNER JOIN SALES_ORDER ON SALES_ORDER_DETAILS.S_ORDER_NO = SALES_ORDER.S_ORDER_NO
WHERE SALES_ORDER.ORDER_STATUS LIKE 'IN PROCESS';

4. Find out the names of clients who have purchased ‘CD DRIVE’.

Query:

SELECT CLIENT_MASTER.NAME
FROM CLIENT_MASTER
INNER JOIN SALES_ORDER ON CLIENT_MASTER.CLIENT_NO = SALES_ORDER.CLIENT_NO
INNER JOIN SALES_ORDER_DETAILS S ON SALES_ORDER.S_ORDER_NO = S.S_ORDER_NO
INNER JOIN PRODUCT_MASTER MASTER2 ON S.PRODUCT_NO = MASTER2.PRODUCT_NO WHERE
MASTER2.DESCRIPTION LIKE 'CD_DRIVE';

5. List the product_no and s_order_no of customers haaving qty ordered less
than 5 from the order details table for the product “1.44 floppies”.

Query:

SELECT SALES_ORDER_DETAILS.S_ORDER_NO,SALES_ORDER_DETAILS.PRODUCT_NO
FROM SALES_ORDER_DETAILS
INNER JOIN PRODUCT_MASTER MASTER2 ON SALES_ORDER_DETAILS.PRODUCT_NO =
MASTER2.PRODUCT_NO WHERE
MASTER2.DESCRIPTION LIKE '1.44FLOPPIES' AND SALES_ORDER_DETAILS.QTY_ORDER <5;
6. Find the products and their quantities for the orders placed
by ‘Vandan Saitwal ’ and “Ivan Bayross”.

Query:

SELECT PRODUCT_MASTER.DESCRIPTION, S.QTY_ORDER


FROM PRODUCT_MASTER
INNER JOIN SALES_ORDER_DETAILS S ON PRODUCT_MASTER.PRODUCT_NO = S.PRODUCT_NO
INNER JOIN SALES_ORDER SO ON S.S_ORDER_NO = SO.S_ORDER_NO
INNER JOIN CLIENT_MASTER ON SO.CLIENT_NO = SYSTEM.CLIENT_MASTER.CLIENT_NO WHERE
CLIENT_MASTER.NAME LIKE 'VANDAN' OR CLIENT_MASTER.NAME LIKE 'IVAN';

7. Find the products and their quantities for the orders placed by
client_no “ C00001” and “C00002”.

Query:

SELECT PRODUCT_MASTER.DESCRIPTION, S.QTY_ORDER


FROM PRODUCT_MASTER
INNER JOIN SALES_ORDER_DETAILS S ON PRODUCT_MASTER.PRODUCT_NO = S.PRODUCT_NO
INNER JOIN SALES_ORDER SO ON S.S_ORDER_NO = SO.S_ORDER_NO
INNER JOIN CLIENT_MASTER ON SO.CLIENT_NO = SYSTEM.CLIENT_MASTER.CLIENT_NO WHERE
CLIENT_MASTER.CLIENT_NO LIKE '0001' OR CLIENT_MASTER.CLIENT_NO LIKE '0002';

8. Find the order No,, Client No and salesman No. where a client has been
received by more than one salesman.

Query:

SELECT SALES_ORDER.CLIENT_NO,SALES_ORDER.SALESMAN_NO,SALES_ORDER.S_ORDER_NO FROM


SALES_ORDER WHERE SALES_ORDER.CLIENT_NO = (SELECT SALES_ORDER.CLIENT_NO
FROM SALES_ORDER GROUP BY SALES_ORDER.CLIENT_NO
HAVING COUNT(SALES_ORDER.CLIENT_NO)>1);
9. Display the s_order_date in the format “dd-mm-yy” e.g. “12- feb-96”.

Query:

SELECT TO_CHAR(SYSDATE, 'DD/MM/YY')


FROM DUAL;

10. Find the date , 15 days after date.

Query:

SELECT SYSDATE+15 MYDATE FROM DUAL;


Experiment 6
Date:

Objective:
To implement the concepts of grouping of data.

Software Used:
Oracle 12c & DataGrip IDE

Theory:

Grouping Data From Tables:


There are circumstances where we would like to apply the aggregate function not only to a single
set of tuples, but also to a group of sets of tuples, we specify this wish in SQL using the group by
clause. The attribute or attributes given in the group by clause are used to form group. Tuples
with the same value on all attributes in the group by clause are placed in one group.
Syntax:
SELECT columnname, columnname
FROM tablename
GROUP BY columnname;
At times it is useful to state a condition that applies to groups rather than to tuples. For example
we might be interested in only those branches where the average account balance is more than
1200. This condition does not apply to a single tuple, rather it applies to each group constructed
by the GROUP BY clause. To express such Questionry, we use the having clause of SQL. SQL
applies predicates in the having may be used.
Syntax:
SELECT columnname, columnname
FROM tablename
GROUP BY columnname;
HAVING searchcondition;

Questionnaire’s:

Q1.- Print the description and total quantity sold for each product.
Q2.- Find the value of each product sold.
Q3.- Calculate the average quantity sold for each client that has a maximum order value of 15000.
Q4.- Find out the products which has been sold to Ivan.
Q5.- Find the names of clients who have ‘CD Drive’.
Q6.- Find the products and their quantities for the orders placed by ‘Vandana’ and ‘Ivan’.
Q7.- Select product_no, total qty_ordered for each product.
Q8.- Select product_no, product description and qty ordered for each product.
Q9.- Display the order number and day on which clients placed their order.
Q10.- Display the month and Date when the order must be delivered.

Output:

i. Print the description and total quantity sold for each product.

Query:

SELECT DISTINCT PRODUCT_MASTER.DESCRIPTION,SUM(SALES_ORDER_DETAILS.QTY_ORDER)


FROM PRODUCT_MASTER
INNER JOIN SALES_ORDER_DETAILS ON PRODUCT_MASTER.PRODUCT_NO =
SALES_ORDER_DETAILS.PRODUCT_NO
GROUP BY PRODUCT_MASTER.DESCRIPTION;

ii. Find the value of each product sold.

Query:

SELECT DISTINCT PRODUCT_MASTER.DESCRIPTION,SALES_ORDER_DETAILS.PRODUCT_RATE


FROM PRODUCT_MASTER
INNER JOIN SALES_ORDER_DETAILS ON PRODUCT_MASTER.PRODUCT_NO =
SALES_ORDER_DETAILS.PRODUCT_NO;
iii. Calculate the average quantity sold for each client that has a
maximum order value of 15000.

Query:

SELECT CLIENT_MASTER.NAME,AVG(DISTINCT SALES_ORDER_DETAILS.QTY_ORDER)


FROM SALES_ORDER_DETAILS
INNER JOIN SALES_ORDER S on SALES_ORDER_DETAILS.S_ORDER_NO = S.S_ORDER_NO
INNER JOIN CLIENT_MASTER ON S.CLIENT_NO= CLIENT_MASTER.CLIENT_NO
GROUP BY CLIENT_MASTER.NAME,SALES_ORDER_DETAILS.S_ORDER_NO
HAVING SUM(DISTINCT SALES_ORDER_DETAILS.PRODUCT_RATE ) >15000;

iv. Find out the products which has been sold to Ivan.

Query:

SELECT PRODUCT_MASTER.DESCRIPTION
FROM PRODUCT_MASTER
INNER JOIN SALES_ORDER_DETAILS ON PRODUCT_MASTER.PRODUCT_NO =
SALES_ORDER_DETAILS.PRODUCT_NO
INNER JOIN SALES_ORDER ON SALES_ORDER_DETAILS.S_ORDER_NO = SALES_ORDER.S_ORDER_NO
INNER JOIN CLIENT_MASTER ON SALES_ORDER.CLIENT_NO = CLIENT_MASTER.CLIENT_NO WHERE
CLIENT_MASTER.NAME LIKE 'ivan';
v. Find the names of clients who have ‘CD Drive’.

Query:

SELECT CLIENT_MASTER.NAME
FROM SALES_ORDER_DETAILS
INNER JOIN SALES_ORDER ON SALES_ORDER_DETAILS.S_ORDER_NO = SALES_ORDER.S_ORDER_NO
INNER JOIN CLIENT_MASTER ON SALES_ORDER.CLIENT_NO= CLIENT_MASTER.CLIENT_NO
INNER JOIN PRODUCT_MASTER MASTER2 on SALES_ORDER_DETAILS.PRODUCT_NO =
MASTER2.PRODUCT_NO WHERE
MASTER2.DESCRIPTION LIKE 'CD_drive';

vi. Find the products and their quantities for the orders placed by ‘Vandana’ and ‘Ivan’.

Query:

SELECT PRODUCT_MASTER.DESCRIPTION, S.QTY_ORDER


FROM PRODUCT_MASTER
INNER JOIN SALES_ORDER_DETAILS S on PRODUCT_MASTER.PRODUCT_NO = S.PRODUCT_NO
INNER JOIN SALES_ORDER SO on S.S_ORDER_NO = SO.S_ORDER_NO
INNER JOIN CLIENT_MASTER ON SO.CLIENT_NO = SYSTEM.CLIENT_MASTER.CLIENT_NO WHERE
CLIENT_MASTER.NAME LIKE 'Vandan' or CLIENT_MASTER.NAME like 'ivan';
vii. Select product_no, total qty_ordered for each product.

Query:

SELECT DISTINCT PRODUCT_MASTER.PRODUCT_NO, SUM(S.QTY_ORDER)


FROM PRODUCT_MASTER
INNER JOIN SALES_ORDER_DETAILS S on PRODUCT_MASTER.PRODUCT_NO = S.PRODUCT_NO
INNER JOIN SALES_ORDER SO on S.S_ORDER_NO = SO.S_ORDER_NO
INNER JOIN CLIENT_MASTER ON SO.CLIENT_NO = SYSTEM.CLIENT_MASTER.CLIENT_NO
GROUP BY PRODUCT_MASTER.PRODUCT_NO;

viii. Select product_no, product description and qty ordered for each product.

Query:

SELECT DISTINCT PRODUCT_MASTER.PRODUCT_NO,PRODUCT_MASTER.DESCRIPTION,


SUM(S.QTY_ORDER)
FROM PRODUCT_MASTER
INNER JOIN SALES_ORDER_DETAILS S on PRODUCT_MASTER.PRODUCT_NO = S.PRODUCT_NO
INNER JOIN SALES_ORDER SO on S.S_ORDER_NO = SO.S_ORDER_NO
INNER JOIN CLIENT_MASTER ON SO.CLIENT_NO = SYSTEM.CLIENT_MASTER.CLIENT_NO
GROUP BY PRODUCT_MASTER.PRODUCT_NO,PRODUCT_MASTER.DESCRIPTION;
ix. Select product_no, product description and qty ordered for each product.

Query:

SELECT TO_CHAR(SALES_ORDER.S_ORDER_DATE,'DAY'),SALES_ORDER.S_ORDER_NO
FROM SALES_ORDER;

x. Display the month and Date when the order must be delivered.

Query:

SELECT TO_CHAR(SALES_ORDER.S_ORDER_DATE,'MONTH'),SALES_ORDER.DELY_DATE
FROM SALES_ORDER;
Experiment 7
Date:

Objective:
To implement the concepts of view and indexes.

Software Used:
Oracle 12c & DataGrip IDE

Theory:

Indexes:
An index is an ordered list of content of a column or group of columns in a table. An index created
on the single column of the table is called simple index. When multiple table columns are
included in the index it is called composite index.

Creating an Index for a table:-

Syntax (Simple)
CREATE INDEX index_name
ON tablename(column name);
Composite Index:-
CREATE INDEX index_name
ON tablename(columnname,columnname);
Creating an UniQuestion Index:-
CREATE UNIQUESTION INDEX indexfilename
ON tablename(columnname);
Dropping Indexes:-
An index can be dropped by using DROP INDEX
Syntax:-
DROP INDEX indexfilename;

Views:
Logical data is how we want to see the current data in our database. Physical data is how
this data is actually placed in our database.
Views are masks placed upon tables. This allows the programmer to develop a method
via which we can display predetermined data to users according to our desire.
Views may be created fore the following reasons:

1. The DBA stores the views as a definition only. Hence there is no duplication of data.
2. Simplifies Questionries.
3. Can be Questionried as a base table itself.
4. Provides data security.
5. Avoids data redundancy.

Creation of Views:-

Syntax:-
CREATE VIEW viewname AS
SELECT columnname,columnname
FROM tablename
WHERE columnname=expression_list;

Renaming the columns of a view:-

Syntax:-
CREATE VIEW viewname AS
SELECT newcolumnname….
FROM tablename
WHERE columnname=expression_list;

Selecting a data set from a view-

Syntax:-
SELECT columnname, columnname
FROM viewname
WHERE search condition;

Destroying a view-

Syntax:-
DROP VIEW viewname;

Questionnaire’s:

Q1. Create an index on the table client_master, field client_no.


Q2. Create an index on the sales_order, field s_order_no.
Q3. Create an composite index on the sales_order_details table for the columns
s_order_no and product_no.
Q4. Create an composite index ch_index on challan_header table for the columns
challan no and s_order_no.
Q5. Create an uniQuestion index on the table salesman_master, field salesman_no.
Q6. Drop index ch_index on table challan_header.
Q7. Create view on salesman_master whose sal_amt is less than 3500.
Q8. Create a view client_view on client_master and rename the columns as name, add1,
add2, city, pcode, state respectively.
Q9. Select the client names from client_view who lives in city ‘Bombay’.
Q10. Drop the view client_view.

Output:

i. Create an index on the table client_master, field client_no.

Query:

CREATE INDEX SYS_C0012103


ON CLIENT_MASTER(CLIENT_NO);

ii. Create an index on the sales_order, field s_order_no.

Query:

CREATE INDEX SYS_C0012070


ON SALES_ORDER(S_ORDER_NO);

iii. Create an composite index on the sales_order_details table for the columns
s_order_no and product_no.

Query:

CREATE INDEX PK_SOD


ON SALES_ORDER_DETAILS(S_ORDER_NO,PRODUCT_NO);

iv. Create an composite index ch_index on challan_header table for the columns
challan no and s_order_no.

Query:

CREATE INDEX CH_INDEX


ON CHALLAN_HEADER (CHALLAN_NO,S_ORDER_NO);

v. Create an uniQuestion index on the table salesman_master, field salesman_no.

Query:
CREATE UNIQUE INDEX SYS_C0012063
ON SALES_MASTER (SALESMAN_NO);

vi. Drop index ch_index on table challan_header.

Query:

DROP INDEX CH_INDEX;

vii. Create view on salesman_master whose sal_amt is less than 3500.

Query:

CREATE VIEW SPSAL AS


SELECT * FROM SALES_MASTER
WHERE SALES_MASTER.SAL_AMT <3500;

viii. Create a view client_view on client_master and rename the columns


as name, add1, add2, city, pcode, state respectively.

Query:

CREATE VIEW CLIENT_VIEW AS SELECT CLIENT_MASTER.CLIENT_NO


AS CNO,CLIENT_MASTER.NAME AS CNAME, CLIENT_MASTER.ADDRESS1 AS ADD1,
CLIENT_MASTER.ADDRESS2 AS ADD2, CLIENT_MASTER.BAL_DUE AS BD,CLIENT_MASTER.CITY AS
CCITY,CLIENT_MASTER.STATE CSTATE, CLIENT_MASTER.PINCODE PCODE,
CLIENT_MASTER.PHONE_NO AS PH FROM CLIENT_MASTER;
ix. Select the client names from client_view who lives in city ‘Bombay’.

Query:

SELECT * FROM CLIENT_VIEW WHERE CCITY IN 'Bombay';

x. Drop the view client_view.

Query:

DROP VIEW CLIENT_VIEW;


Experiment 8

Date:

Objective:
To implement the concepts of union, intersection and minus.

Software Used:
Oracle 12c & DataGrip IDE

Theory:

UNION

It returns a union of two select statements. It is returning unique (distinct) values of


them.

SELECT * FROM table1


UNION
SELECT * FROM table2;

UNION ALL
Similar to UNION just that UNION ALL returns also the duplicated values.

SELECT * FROM table1


UNION ALL
SELECT * FROM table2;

When using UNION and UNION ALL columns in SELECT statements need to match.
This would return an error:

SELECT column1 FROM table1


UNION
SELECT * FROM table2;

MINUS

MINUS (also known as EXCEPT) returns the difference between the first and second
SELECT statement. It is the one where we need to be careful which statement will be
put first, cause we will get only those results that are in the first SELECT statement
and not in the second.

SELECT * FROM table1


MINUS
SELECT * FROM table2;

INTERSECT

INTERSECT is opposite from MINUS as it returns us the results that are both to be
found in first and second SELECT statement.
SELECT * FROM table1
INTERSECT
SELECT * FROM table2;

EXAMPLE

There is an interesting example that us use SET OPERATORS to compare whether two
tables have identical values, testing symetric difference. If result of this entire query
returns no rows, it will mean that they are identical.

(SELECT * FROM table1


MINUS
SELECT * FROM table2)
UNION
(SELECT * FROM table2
MINUS
SELECT * FROM table1);

COMPOUND QUERIES

Each query in a compound query will project its own list of selected columns. These
lists must have the same number of elements, be nominated in the same sequence,
and be of broadly similar data type. They do not have to have the same names (or
column aliases), nor do they need to come from the same tables (or subqueries). If
the column names (or aliases) are different, the result set of the compound query
will have columns named as they were in the first query.

The corresponding columns in the queries that make up a compound query must be
of the same data type group. The result set of the compound query will have
columns with the higher level of precision.

UNION, MINUS, and INTERSECT will always combine the results sets of the input
queries, then sort the results to remove duplicate rows. If the sort order (which is
ascending, based on the order in which the columns happen to
appear in the select lists) is not the order you want, it is possible to put a single
ORDER BY clause at the end of the compound query. It is not possible to use ORDER
BY in any of the queries that make up the whole compound query, as this would
disrupt the sorting that is necessary to remove duplicates. UNION ALL is the
exception to the sorting-no-duplicates rule: the result sets of the two input queries
will be concatenated to form the result of the compound query.

Control the Order of Rows Returned

It is not possible to use ORDER BY in the individual queries that make a


compound query. An ORDER BY clause can be appended to the end of a compound
query.

Questionnaire’s:
1. Select distinct s_order_no from sales order and sales order no.
2. Select all s_order_no from sales order and sales order no.
3. Select client no’s of only those clients who have a sales order.
4. Select client no.’s of clients who have no sales order.

Output:

i. Select distinct s_order_no from sales order and sales order no.

Query:

SELECT S_ORDER_NO FROM SALES_ORDER


UNION
SELECT S_ORDER_NO FROM SALES_ORDER_DETAILS;
ii. Select all s_order_no from sales order and sales order no.

Query:

SELECT S_ORDER_NO FROM SALES_ORDER


UNION ALL
SELECT S_ORDER_NO FROM SALES_ORDER_DETAILS;

iii. Select client no’s of only those clients who have a sales order.

Query:

SELECT CLIENT_NO FROM SALES_ORDER


INTERSECT
SELECT CLIENT_NO FROM CLIENT_MASTER;
iv. Select client no.’s of clients who have no sales order.

Query:

SELECT CLIENT_NO FROM CLIENT_MASTER


MINUS
SELECT CLIENT_NO FROM SALES_ORDER;
Experiment 9

Date:

Objective:
To implement the basics of pl sql.

Software Used:
Oracle 12c

Theory:

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


languages. It was developed by Oracle Corporation in the early 90's to enhance the
capabilities of SQL. PL/SQL is one of three key programming languages embedded in
the Oracle Database, along with SQL itself and Java.

The PL/SQL programming language was developed by Oracle Corporation in the late
1980s as procedural extension language for SQL and the Oracle relational database.
Following are certain notable facts about PL/SQL −
 PL/SQL is a completely portable, high-performance transaction-processing
language.
 PL/SQL provides a built-in, interpreted and OS independent programming
environment.
 PL/SQL can also directly be called from the command-line SQL*Plus interface.
 Direct call can also be made from external programming language calls to
database.
 PL/SQL's general syntax is based on that of ADA and Pascal programming
language.
 Apart from Oracle, PL/SQL is available in TimesTen in-memory
database and IBM DB2.
Features of PL/SQL

PL/SQL has the following features −

 PL/SQL is tightly integrated with SQL.


 It offers extensive error checking.
 It offers numerous data types.
 It offers a variety of programming structures.
 It supports structured programming through functions and procedures.
 It supports object-oriented programming.
 It supports the development of web applications and server pages.

Advantages of PL/SQL

PL/SQL has the following advantages −


 SQL is the standard database language and PL/SQL is strongly integrated with
SQL. PL/SQL supports both static and dynamic SQL. Static SQL supports DML
operations and transaction control from PL/SQL block. In Dynamic SQL, SQL
allows embedding DDL statements in PL/SQL blocks.
 PL/SQL allows sending an entire block of statements to the database at one
time. This reduces network traffic and provides high performance for the
applications.
 PL/SQL gives high productivity to programmers as it can query, transform, and
update data in a database.
 PL/SQL saves time on design and debugging by strong features, such as
exception handling, encapsulation, data hiding, and object-oriented data
types.
 Applications written in PL/SQL are fully portable.
 PL/SQL provides high security level.
 PL/SQL provides access to predefined SQL packages.
 PL/SQL provides support for Object-Oriented Programming.
 PL/SQL provides support for developing Web Applications and Server Pages.

Every PL/SQL statement ends with a semicolon (;). PL/SQL blocks can be nested within
other PL/SQL blocks using BEGIN and END. Following is the basic structure of a
PL/SQL block −
DECLARE
<declarations section>
BEGIN
<executable command(s)>
EXCEPTION
<exception handling>
END;

Questionnaire’s:

1. Print a message on the output console.


2. Add two numbers and display the result.
3. Print the average of three no.’s.
4. Write a PL/SQL code block to find factorial of a number.
5. Print the Sum of first ten natural no.’s.
6. Print the name and salary of the employee John.

Output:

i. Print a message on the output console.

Query:

DECLARE
MESSAGE VARCHAR2(20):= 'HELLO, WORLD!';
BEGIN
DBMS_OUTPUT.PUT_LINE(MESSAGE);
END;
ii. Add two numbers and display the result.

Query:

DECLARE
A NUMBER:=5;
B NUMBER:=6;
C INTEGER;
BEGIN
C:= A+B;
DBMS_OUTPUT.PUT_LINE('C: ' || C);
END;

iii. Print the average of three no.’s

Query:

DECLARE
A NUMBER:=&A;
B NUMBER:=&B;
C NUMBER:=&C;
SM NUMBER;
AV NUMBER;
BEGIN
SM:=A+B+C;
AV:=SM/3;
DBMS_OUTPUT.PUT_LINE('SUM = '||SM);
DBMS_OUTPUT.PUT_LINE('AVERAGE = '||AV);
END;
iv. Write a PL/SQL code block to find factorial of a number.

Query:

DECLARE
N NUMBER;
I NUMBER;
F NUMBER:=1;
BEGIN
N:=&N;
FOR I IN 1..N
LOOP
F:=F*I;
END LOOP;
DBMS_OUTPUT.PUT_LINE(N||'! = '||F);
END;

v. Print the Sum of first ten natural no.’s.

Query:

DECLARE
N NUMBER:=10;
I NUMBER;
SUM1 NUMBER:=0;
BEGIN
FOR I IN 1..N
LOOP
SUM1:=SUM1+I;
END LOOP;
DBMS_OUTPUT.PUT_LINE('SUM OF FIRST TEN NATURAL NO IS: ' || SUM1);
END;
vi. Print the name and salary of the employee John.

Query:

DECLARE
B EMP.NAME%TYPE;
C EMP.SALARY%TYPE;
BEGIN
SELECT NAME,SALARY INTO B,C FROM EMP WHERE NAME = 'JOHN';
DBMS_OUTPUT.PUT_LINE(B || ' ' || C);
END;
Experiment 10

Date:

Objective:
To implement the concept of cursors.

Software Used:
Oracle 12c

Theory:

Oracle creates a memory area, known as the context area, for processing an SQL
statement, which contains all the information needed for processing the statement;
for example, the number of rows processed, etc.
A cursor is a pointer to this context area. PL/SQL controls the context area through a
cursor. A cursor holds the rows (one or more) returned by a SQL statement. The set
of rows the cursor holds is referred to as the active set.
You can name a cursor so that it could be referred to in a program to fetch and process
the rows returned by the SQL statement, one at a time. There are two types of cursors

 Implicit cursors
 Explicit cursors

Implicit Cursors

Implicit cursors are automatically created by Oracle whenever an SQL statement is


executed, when there is no explicit cursor for the statement. Programmers cannot
control the implicit cursors and the information in it.
Whenever a DML statement (INSERT, UPDATE and DELETE) is issued, an implicit
cursor is associated with this statement. For INSERT operations, the cursor holds the
data that needs to be inserted. For UPDATE and DELETE operations, the cursor
identifies the rows that would be affected.
In PL/SQL, you can refer to the most recent implicit cursor as the SQL cursor, which
always has attributes such as %FOUND, %ISOPEN, %NOTFOUND,
and %ROWCOUNT.

The SQL cursor has additional attributes, %BULK_ROWCOUNT and


%BULK_EXCEPTIONS, designed for use with the FORALL statement. The following
table provides the description of the most used attributes –

S.No Attribute & Description

%FOUND
1
Returns TRUE if an INSERT, UPDATE, or DELETE statement affected one or more rows or a
SELECT INTO statement returned one or more rows. Otherwise, it returns FALSE.

%NOTFOUND

2 The logical opposite of %FOUND. It returns TRUE if an INSERT, UPDATE, or DELETE statement
affected no rows, or a SELECT INTO statement returned no rows. Otherwise, it returns FALSE.

%ISOPEN

3 Always returns FALSE for implicit cursors, because Oracle closes the SQL cursor automatically
after executing its associated SQL statement.

%ROWCOUNT

4 Returns the number of rows affected by an INSERT, UPDATE, or DELETE statement, or returned
by a SELECT INTO statement.

Explicit Cursors

Explicit cursors are programmer-defined cursors for gaining more control over
the context area. An explicit cursor should be defined in the declaration section of
the PL/SQL Block. It is created on a SELECT Statement which returns more than one
row.
The syntax for creating an explicit cursor is –
CURSOR cursor_name IS select_statement;

Working with an explicit cursor includes the following steps −

 Declaring the cursor for initializing the memory


 Opening the cursor for allocating the memory
 Fetching the cursor for retrieving the data
 Closing the cursor to release the allocated memory

Declaring the Cursor


Declaring the cursor defines the cursor with a name and the associated SELECT
statement. For example −

CURSOR c_customers IS

SELECT id, name, address FROM customers;

Opening the Cursor


Opening the cursor allocates the memory for the cursor and makes it ready for
fetching the rows returned by the SQL statement into it. For example, we will open
the above defined cursor as follows −

OPEN c_customers;

Fetching the Cursor


Fetching the cursor involves accessing one row at a time. For example, we will fetch
rows from the above-opened cursor as follows −

FETCH c_customers INTO c_id, c_name, c_addr;

Closing the Cursor


Closing the cursor means releasing the allocated memory. For example, we will close
the above-opened cursor as follows −

CLOSE c_customers;
Questionnaire’s:

1. Using explicit cursor to find records of all employees.


2. Using implicit cursor to find specific records of an employee alex.
3. Validate the input using exception.
4. Update the salary of every employee’s with 500 using exception.

Output:

i. Using explicit cursor to find records of all employees.

Query:

DECLARE
A EMP.NAME%TYPE;
CURSOR C1 IS SELECT NAME FROM EMP;
BEGIN
OPEN C1;
LOOP
FETCH C1 INTO A;
EXIT WHEN C1%NOTFOUND;
DBMS_OUTPUT.PUT_LINE('EMPLOYEE' || ' ' || A);
END LOOP;
CLOSE C1;
END;

ii. Using implicit cursor to find specific records of an employee alex.

Query:

DECLARE
EMPREC EMP%ROWTYPE;
BEGIN
SELECT * INTO EMPREC FROM EMP WHERE NAME = 'ALEX';
DBMS_OUTPUT.PUT_LINE(EMPREC.EMP_ID || ' ' || EMPREC.NAME || ' ' || EMPREC.SALARY);
END;
iii. Validate the input using exception.

Query:

DECLARE
S NUMBER:=&S;
EX EXCEPTION;
BEGIN
IF (S<=10) THEN RAISE EX;
END IF;
EXCEPTION
WHEN EX THEN DBMS_OUTPUT.PUT_LINE('ID MUST BE GREATER THAN 10');
END;

When s < 10

When s >10
iv. Update the salary of every employee’s with 500 using exception.

Query:

DECLARE
TNO NUMBER(3);
BEGIN
UPDATE EMP SET SALARY = SALARY + 500;
IF SQL%NOTFOUND
THEN DBMS_OUTPUT.PUT_LINE('NO RECORDS FOUND');
END IF;
IF SQL%FOUND THEN TNO:= SQL%ROWCOUNT;
DBMS_OUTPUT.PUT_LINE(TNO);
END IF;
END;

Before updating:

After updating:
Experiment 11

Date:

Objective:
To implement the concept of functions and procedures.

Software Used:
Oracle 12c

Theory:

PROCEDURES:
A subprogram is a program unit/module that performs a particular task. These
subprograms are combined to form larger programs. This is basically called the
'Modular design'. A subprogram can be invoked by another subprogram or program
which is called the calling program.
A subprogram can be created −

 At the schema level


 Inside a package
 Inside a PL/SQL block
At the schema level, subprogram is a standalone subprogram. It is created with the
CREATE PROCEDURE or the CREATE FUNCTION statement. It is stored in the database
and can be deleted with the DROP PROCEDURE or DROP FUNCTION statement.
A subprogram created inside a package is a packaged subprogram. It is stored in the
database and can be deleted only when the package is deleted with the DROP
PACKAGE statement. We will discuss packages in the chapter 'PL/SQL - Packages'.
PL/SQL subprograms are named PL/SQL blocks that can be invoked with a set of
parameters. PL/SQL provides two kinds of subprograms −
 Functions − These subprograms return a single value; mainly used to compute
and return a value.
 Procedures − These subprograms do not return a value directly; mainly used to
perform an action.
Parts of a PL/SQL Subprogram
Each PL/SQL subprogram has a name, and may also have a parameter list. Like
anonymous PL/SQL blocks, the named blocks will also have the following three parts-

S.No Parts & Description

Declarative Part
It is an optional part. However, the declarative part for a subprogram does
1 not start with the DECLARE keyword. It contains declarations of types,
cursors, constants, variables, exceptions, and nested subprograms. These
items are local to the subprogram and cease to exist when the subprogram
completes execution.

Executable Part
2 This is a mandatory part and contains statements that perform the
designated action.

Exception-handling
3 This is again an optional part. It contains the code that handles run-time
errors.

Creating a Procedure
A procedure is created with the CREATE OR REPLACE PROCEDUREstatement. The
simplified syntax for the CREATE OR REPLACE PROCEDURE statement is as follows −

CREATE [OR REPLACE] PROCEDURE procedure_name

[(parameter_name [IN | OUT | IN OUT] type [, ...])]

{IS | AS}

BEGIN

< procedure_body >

END procedure_name;
Where,
 procedure-name specifies the name of the procedure.
 [OR REPLACE] option allows the modification of an existing procedure.
 The optional parameter list contains name, mode and types of the
parameters. IN represents the value that will be passed from outside and OUT
represents the parameter that will be used to return a value outside of the
procedure.
 procedure-body contains the executable part.
 The AS keyword is used instead of the IS keyword for creating a standalone
procedure.
Executing a Standalone Procedure
A standalone procedure can be called in two ways −
 Using the EXECUTE keyword
 Calling the name of the procedure from a PL/SQL block
The above procedure named 'greetings' can be called with the EXECUTE keyword as
EXECUTE procedure;

Deleting a Standalone Procedure


A standalone procedure is deleted with the DROP PROCEDURE statement. Syntax
for deleting a procedure is
DROP PROCEDURE procedure-name;

Parameter Modes in PL/SQL Subprograms

The following table lists out the parameter modes in PL/SQL subprograms

S.No Parameter Mode & Description

IN

1
An IN parameter lets you pass a value to the subprogram. It is a read-only
parameter. Inside the subprogram, an IN parameter acts like a constant. It
cannot be assigned a value. You can pass a constant, literal, initialized
variable, or expression as an IN parameter. You can also initialize it to a
default value; however, in that case, it is omitted from the subprogram
call. It is the default mode of parameter passing. Parameters are passed
by reference.

OUT
An OUT parameter returns a value to the calling program. Inside the
2 subprogram, an OUT parameter acts like a variable. You can change its value
and reference the value after assigning it. The actual parameter must be
variable and it is passed by value.

IN OUT
An IN OUT parameter passes an initial value to a subprogram and returns
an updated value to the caller. It can be assigned a value and the value can
3 be read.
The actual parameter corresponding to an IN OUT formal parameter must
be a variable, not a constant or an expression. Formal parameter must be
assigned a value. Actual parameter is passed by value.

Methods for Passing Parameters

Actual parameters can be passed in three ways

 Positional notation
 Named notation
 Mixed notation

Positional Notation
In positional notation, you can call the procedure as
findMin(a, b, c, d);

In positional notation, the first actual parameter is substituted for the first formal
parameter; the second actual parameter is substituted for the second formal
parameter, and so on. So, a is substituted for x, b is substituted for y, c is substituted
for z and d is substituted for m.
Named Notation
In named notation, the actual parameter is associated with the formal parameter
using the arrow symbol ( => ). The procedure call will be like the following −
findMin(x => a, y => b, z => c, m => d);

Mixed Notation
In mixed notation, you can mix both notations in procedure call; however, the
positional notation should precede the named notation.
The following call is legal
findMin(a, b, c, m => d);

However, this is not legal:


findMin(x => a, b, c, d);

Function:
A function is same as a procedure except that it returns a value. Therefore,
all the discussions of the previous chapter are true for functions too.

Creating a Function
A standalone function is created using the CREATE FUNCTION statement. The
simplified syntax for the CREATE OR REPLACE PROCEDURE statement is as follows –

CREATE [OR REPLACE] FUNCTION function_name


[(parameter_name [IN | OUT | IN OUT] type [, ...])]
RETURN return_datatype
{IS | AS}
BEGIN
< function_body >
END [function_name];

Where,

 function-name specifies the name of the function.


 [OR REPLACE] option allows the modification of an existing function.
 The optional parameter list contains name, mode and types of the parameters.
IN represents the value that will be passed from outside and OUT represents
the parameter that will be used to return a value outside of the procedure.
 The function must contain a return statement.
 The RETURN clause specifies the data type you are going to return from the
function.
 function-body contains the executable part.
 The AS keyword is used instead of the IS keyword for creating a standalone
function.

Calling a Function
While creating a function, you give a definition of what the function has to do. To use
a function, you will have to call that function to perform the defined task. When a
program calls a function, the program control is transferred to the called function.
A called function performs the defined task and when its return statement is executed
or when the last end statement is reached, it returns the program control back to the
main program.
To call a function, you simply need to pass the required parameters along with the
function name and if the function returns a value, then you can store the returned
value.

PL/SQL Recursive Functions


We have seen that a program or subprogram may call another subprogram. When a
subprogram calls itself, it is referred to as a recursive call and the process is known
as recursion.

Questionnaire’s:

1. Write a procedure to display welcome message with name.


2. Write a procedure to insert a new user in table emp.
3. Write a function to find minimum of two numbers.
4. Write a procedure to find the square of a given number.
5. Write a function to find factorial of a number.
Output:

i. Write a procedure to display welcome message with name.

Query:

CREATE OR REPLACE PROCEDURE WELCOME_MSG(P_NAME IN VARCHAR2)


IS
BEGIN
DBMS_OUTPUT.PUT_LINE('WELCOME '|| P_NAME);
END;

EXEC WELCOME_MSG ('HASNAIN');

ii. Write a procedure to insert a new user in table emp.

Query:

CREATE OR REPLACE PROCEDURE INSERTUSER (ID IN NUMBER,ENAME IN VARCHAR2)


AS
BEGIN
INSERT INTO EMP(EMP_ID,NAME) VALUES(ID,ENAME);
END;

BEGIN
INSERTUSER(&A,'&B');
DBMS_OUTPUT.PUT_LINE('RECORDS INSERTED SUCCESSFULLY');
END;
iii. Write a function to find minimum of two numbers.

Query:

CREATE OR REPLACE FUNCTION F2 (X IN NUMBER,Y IN NUMBER) RETURN


NUMBER IS Z NUMBER;
BEGIN
IF X<Y THEN Z:=X;
ELSE Z:=Y;
END IF;
RETURN Z;
END;

DECLARE
C NUMBER(8);
BEGIN
C:=F2(20,30);
DBMS_OUTPUT.PUT_LINE('OUTPUT ' || C);
END;

iv. Write a procedure to find the square of a given number.

Query:

CREATE OR REPLACE PROCEDURE SQUARENUM(X IN OUT NUMBER) AS


BEGIN
X := X * X;
END;

DECLARE
A NUMBER;
BEGIN
A:= 23;
SQUARENUM(A);
DBMS_OUTPUT.PUT_LINE(' SQUARE OF (23): ' || A);
END;
v. Write a function to find factorial of a number.

Query:

CREATE OR REPLACE FUNCTION FACT(N NUMBER) RETURN NUMBER IS


I NUMBER(3);
F NUMBER:=1;
BEGIN
FOR I IN 1..N
LOOP
F:=F*I;
END LOOP;
RETURN(F);
END FACT;

DECLARE
F NUMBER(3);
N NUMBER(3):=&N;
BEGIN
F:=FACT(N);
DBMS_OUTPUT.PUT_LINE('FACTORIAL= ' || F);
END;
Experiment 12

Date:

Objective:
To implement the concept of triggers.

Software Used:
Oracle 12c

Theory:
Triggers are stored programs, which are automatically executed or fired when some
events occur. Triggers are, in fact, written to be executed in response to any of the
following events −
 A database manipulation (DML) statement (DELETE, INSERT, or UPDATE)
 A database definition (DDL) statement (CREATE, ALTER, or DROP).
 A database operation (SERVERERROR,LOGON,LOGOFF,STARTUP,
or SHUTDOWN).
Triggers can be defined on the table, view, schema, or database with which the event
is associated.

Benefits of Triggers
Triggers can be written for the following purposes −

 Generating some derived column values automatically


 Enforcing referential integrity
 Event logging and storing information on table access
 Auditing
 Synchronous replication of tables
 Imposing security authorizations
 Preventing invalid transactions
Creating Triggers
The syntax for creating a trigger is −

CREATE [OR REPLACE ] TRIGGER trigger_name

{BEFORE | AFTER | INSTEAD OF }

{INSERT [OR] | UPDATE [OR] | DELETE}

[OF col_name]

ON table_name

[REFERENCING OLD AS o NEW AS n]

[FOR EACH ROW]

WHEN (condition)

DECLARE

Declaration-statements

BEGIN

Executable-statements

EXCEPTION

Exception-handling-statements

END;

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

Example
To start with, we will be using the CUSTOMERS table we had created and used in the
previous chapters −
Select * from customers;

+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
+----+----------+-----+-----------+----------+

The following program creates a row-level trigger for the customers table that would
fire for INSERT or UPDATE or DELETE operations performed on the CUSTOMERS table.
This trigger will display the salary difference between the old values and new values

CREATE OR REPLACE TRIGGER display_salary_changes

BEFORE DELETE OR INSERT OR UPDATE ON customers

FOR EACH ROW

WHEN (NEW.ID > 0)

DECLARE

sal_diff number;

BEGIN

sal_diff := :NEW.salary - :OLD.salary;

dbms_output.put_line('Old salary: ' || :OLD.salary);

dbms_output.put_line('New salary: ' || :NEW.salary);

dbms_output.put_line('Salary difference: ' || sal_diff);

END;

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

The following points need to be considered here −


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

Triggering a Trigger
Let us perform some DML operations on the CUSTOMERS table. Here is one INSERT
statement, which will create a new record in the table −

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)

VALUES (7, 'Kriti', 22, 'HP', 7500.00 );

When a record is created in the CUSTOMERS table, the above create


trigger, display_salary_changes will be fired and it will display the following result −
Old salary:
New salary: 7500
Salary difference:

Because this is a new record, old salary is not available and the above result comes as
null. Let us now perform one more DML operation on the CUSTOMERS table. The
UPDATE statement will update an existing record in the table −

UPDATE customers

SET salary = salary + 500

WHERE id = 2;
When a record is updated in the CUSTOMERS table, the above create
trigger, display_salary_changes will be fired and it will display the following result –

Old salary: 1500


New salary: 2000
Salary difference: 500
Open Ended Experiment
Query optimisation ( RA )

Date: 10-10-2018

Objective:
To optimize the SQL queries in the best possible manner such that they require
minimum amount of operations and hence space.

Customer (C_ID, C_NAME,C_SECTOR C_ClTY)


Branch (B_ID, B_NAME, B_CITY)
Account (AN, BALANCE, B_ID)
Depositor (C_ID, AN)
Loan (LN, AMOUNT, B_ID)
Borrower (C_ID, LN)

Determine the names of customers who have both account as well as


loan from the bank.

1. Select c_name from customerl where cid in (Select c_id from depositor
INTERSECT select cid from borrower);

i. Select C NAME from Customer


Where C_ID IN { Select C_ID from Depositor
INTERSECT
Select C_ ID from Borrower)

Ans: Temp  {C_ID(Depositor)  C_ID(Borrower))


C_NAME (Customer Temp)

2. Select c_name from customer1 where cid in (Select cid from depositor where cid
(Select cid from borrower));

ii. Select C_NAME from Customer


Where C_ID IN (Select C_ID from Depositor
Where C_ID IN (Select C_ID from Borrower

Ans: Temp  C_ID (Depositor) C_ID (Borrower)


C_Name (Customer Temp)
3. Select cname from customerl where cid in(Select cid from borrower where (Select
cid from depositor));

Ans: Temp  C_ID (Borrower) C_ID {Depositor)


C_Name (Customer Temp)

Das könnte Ihnen auch gefallen