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

Chapter 1 Part 2 Advanced SQL

The document provides information about advanced SQL concepts like controlling program flow, conditional statements, loops, views, stored functions, stored procedures, handling errors and exceptions, and cursors. It also includes examples of SQL queries on sample employee and department tables to retrieve employee names working in a particular department.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
213 views

Chapter 1 Part 2 Advanced SQL

The document provides information about advanced SQL concepts like controlling program flow, conditional statements, loops, views, stored functions, stored procedures, handling errors and exceptions, and cursors. It also includes examples of SQL queries on sample employee and department tables to retrieve employee names working in a particular department.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 70

Advanced SQL

 Controlling the program flow, conditional statements, loops


Views
 Stored Functions Stored Procedures
 Handling errors and exceptions Cursors
 Triggers

Prerequisite
Students should able to solve simple ,nested and queries using
joins
Emp(eno, ename , designation, sal,dno)
Dept(dno, dname, dloc)

eno ename Designation sal dno


dno dname dloc 11 punam Professor 100000 6
6 finance 101 22 Divya Professor 100000 2
2 HR 102 33 Nilima Lecturer 50000 6
3 Admin 103 44 Smita Lecturer 60000 3

1. Display employee names working in HR department

Select ename from dept,emp where dept.dno=emp.dno and dname=‘HR’;


Emp(eno, ename , designation, sal)
Dept(dno, dname, dloc)
There is one to many relationship between department and employee

eno ename Designation sal dno


dno dname dloc 11 punam Professor 100000 6
6 finance 101 22 Divya Professor 100000 2
2 HR 102 33 Nilima Lecturer 50000 6
3 Admin 103 44 Smita Lecturer 60000 3

Ex. Display name of department for employee nilima


Employee (empno int, name varchar, address text , city varchar, deptname varchar)
Project (pno int , pname varchar , status )
There is many to many relationship between employee and project

eno ename city pno pname status


11 punam 1 robotics pending
22 Divya 2 Web completed
applicati
33 Nilima on
44 Smita 3 Android pending
Employee app

Project

eno pno profit


11 1 50000
22 2 100000
33 1 250000
44 3 15000
Emp (eno int, name varchar, address text , city varchar, deptname
varchar)
Proj(pno int , pname varchar , status
emp_pro (eno,pno ,profit)
Joining of tables for above database
1) Join emp and emp_proj
Where emp.eno=emp_proj.eno
2) Join proj and emp_pro
Where proj.pno=emp_proj.pno
3) Join proj and emp
Where emp.eno= emp_proj.eno and proj.pno=emp_proj.pno ;
STUDENT (SNO INTEGER, S_NAME CHAR(30), S_CLASS CHAR(10), S_ADDR CHAR(50))
TEACHER (TNO INTEGER, T_NAME CHAR (20), QUALIFICATION CHAR (15),join_date date)
The relationship is as follows:
STUDENT-TEACHER: M-M with descriptive attribute SUBJECT.
Stud_teach(sno ,tno, subject)

1.Display names of students from sybca class.


Select s_name from student where s_class=‘sybca’;
STUDENT (SNO INTEGER, S_NAME CHAR(30), S_CLASS CHAR(10), S_ADDR CHAR(50))
TEACHER (TNO INTEGER, T_NAME CHAR (20), QUALIFICATION CHAR (15),join_date date)
The relationship is as follows:
STUDENT-TEACHER: M-M with descriptive attribute SUBJECT.
Stud_teach(sno ,tno, subject)

2. Display information of students who have opted


mathematics subject

Select * from student,stud_teach where


student.sno=stu _teach.sno and
subject=‘mathematics’;

//refer examples executed in lab and theory lectures


Views in SQL
 A VIEW in SQL Server is like a virtual table that contains data
from one or multiple tables.
 It does not hold any data and does not exist physically in the
database.
 the view name should be unique in a database. 
 contains a set of predefined SQL queries to fetch data from the
database.
Create a SQL VIEW

Creating a View : CREATE [ OR REPLACE] VIEW name AS query;

Example :

Teacher(tno,tname,qualification,exp)

Create a view to store information of teachers with MCA qualification

Create view teach_info as Select tno,tname,qualification,exp


from teacher where qualification=‘MCA’;
Using Project-Employee database

Emp (eno primary key, ename varchar(20),qualification ,joindate)


Project(pno,pname, ptype,duration,budget)
Emp_pro(eno,pno,no_of_hours,start_date)
1. Create a view over the employee table which contains only employee name
and his qualification and it should be sorted on qualification.

create view empinfo as select ename,qualification from Emp order by


qualification;

2. Create a view containing the project name, project type and start date of the
project

create or replace view proinfo as select pname,ptype,start_date from


project,emp_project where project.pno=emp_pro.pno;
3. Write the following Queries, on the above created views :
a. List different qualifications of employees.

select distinct qualification from empinfo;

b. List the name and type of projects started on 1st April 2014.

Select pname,ptype from pronifo where start_date=‘1/04/2014’;

c. List the names of employees who are qualified as Engineers.

d. Display number of employees of each qualification.


Solving of queries on multiple views

STUDENT (SNO INTEGER, S_NAME CHAR(30), S_CLASS CHAR(10), S_ADDR CHAR(50))


TEACHER (TNO INTEGER, T_NAME CHAR (20), QUALIFICATION CHAR
(15),EXPERIENCE INTEGER)
The relationship is as follows:
Student_teach ( sno,tno,subject)
STUDENT-TEACHER: M-M with descriptive attribute SUBJECT.

1. Create a view containing details of all the teachers teaching the subject
‘Mathematics’.

Create or replace view teachinfo as select teacher.* from


teacher,stud_teach where teacher.tno=stud_teach.tno and
subject=‘mathematics’;
2. Create a view to list the details of all the students who are taught by a teacher having
experience more than 3 years.

Create view studinfo as Select student.* from student,teacher,stud_teach


where student.sno=stud_teach.sno and teacher.tno=stud_teach.tno and exp
>3;

Select sname from studinfo where sclass=‘SYBSC’;


3. Write the following Queries, on the above created views :
a.List the name of the most experienced teacher for
“Mathematics”.

Select tname from teachinfo where exp=(select max(exp)


from teachinfo);
b.List the names of students of ‘S.Y.B.Sc’ class, who are taught by a
teacher having more than 3 years experience.
INSERT ,UPDATE and DELETE operation on views

When you execute an update operation such as INSERT, UPDATE or DELETE,


PosgreSQL will convert this statement into the corresponding statement of the
underlying table.

For insert operation on view , view and table should contain same set of columns
Update operation can be performed if columns to update and columns used in
where condition are available in respective view
Delete operation can be performed if columns used in where condition are
available in respective view
Using Project-Employee database

Emp (eno primary key, ename varchar(20),qualification ,joindate)


Project(pno,pname, ptype,duration,budget)
Emp_pro(eno,pno,no_of_hours,start_date)
1. Create a view over the employee table which contains only employee name and his qualification and it should
be sorted on qualification.

Create view empinfo as select ename,qualification from Emp order by qualification;

2. Create a view containing the project name, project type and start date of the project

Create view proinfo as select pname,ptype,start_date from project,emp_project where project.pno=emp_pro.pno;

Examples for insert, update and delete view refer the notes of Lab assignment on views
Stored Functions
 PostgreSQL allows you to extend the database functionality
with user-defined functions.
 You can create your own custom functions and reuse them in
applications or as part of other database’s workflow.

Example : consider relation emp(eno,ename,salary,city) we can


define functions for below tasks

1.To get the information of employees living in pune city


2. To get the maximum salary earned
1.To get the information employees living in given city
Syntax to create function using plpgsql
create [or replace] function function_name()
returns return_type as
‘declare  First, specify the name of the function after the create function keywords.
 

-- variable declaration If you want to replace the existing function, you can use the or
replace keywords. 
begin  Then, specify the function parameter list surrounded by parentheses after the
-- logic function name. A function can have zero or many parameters.
 Next, specify the datatype of the returned value after the returns keyword.
 
return ;  Declaration of all local variables will go after declare keyword
end;  Function logic will go between begin and end section

‘ language ‘plpgsql’ ;
1. display number of students

2. Display name of student for given Class


Syntax to create function using plpgsql
create [or replace] function
function_name() #display number of students
returns return_type as
create or replace function studcnt()
‘declare returns int as
-- variable declaration '
begin declare
-- logic scount int;
return ; begin
select count(sno) into scount from
end;
student;
‘ language ‘plpgsql’ ; return scount;
end;
' language 'plpgsql';
Syntax to create function using plpgsql
create [or replace] function
function_name() #display number of students for given class
returns return_type as
create or replace function studcntc(classi varchar(20))
‘declare returns int as
-- variable declaration '
begin declare
-- logic scount int;
return ; begin
select count(sno) into scount from student where
end;
class=classi;
‘ language ‘plpgsql’ ; return scount;
end;
' language 'plpgsql';
Home Work :
consider relation employee (eno,ename,salary,city,joindate)

1. Write a function to display maximum salary for given city.

2. Write a function to display salary of given employee

3.write a function to display city of given employee (accept employee name) as parameter
Home Work :
consider relation employee (eno,ename,salary,city,joindate)

1. Write a function to display maximum salary for given city.

2. Write a function to display salary of given employee

3.write a function to display city of given employeeand join date (accept employee name and joindate ) as parameter
write a function to display city of given employeeand join date (accept
employee name and joindate ) as parameter

create function empsal(enamei varchar(20), joindatei date)


returns float as
'
declare
empcity varchar(20);
begin
Select city into empcity from employee where ename=enamei and
joindate=joindatei;
return sal;
End;
'
language 'plpgsql’ ;
Variable Declaration
 Before using a variable, you must declare it in the declaration section of the function

Syntax :
variable_name data_type [:= expression];
 First, specify the name of the variable. It is a good practice to assign a meaningful name to a variable. For example,
instead of naming a variable i you should use index or counter.
 Second, associate a specific data type with the variable. The data type can be any valid data type such as int,numeric,
char,varchar ,date etc.
 Third, optionally assign a default value to a variable. If you don’t do so, the initial value of the variable is NULL.

Example : 1. Create variable to store roll no and initialize it to 1

Rno int := 1;
Row Variables/row type variable
 To store the whole row of a result set returned by the select into statement, you use the row-type variable or
row variable.
 You can declare a variable that has the same datatype as the datatype of the row in a table by using the below
Syntax :
Row_variable tablename%rowtype;
Row_variable viewname%rowtype;

1. Declare a variable that can hold a record of students table

Studinfo student%rowtype;

2. Student (rno,name,class)

Display information of student with rno 10


studinfo student%rowtype
// Example of rowtype variable
3. Create a function to display information of student for given rollno

create or replace function getstudinfo( snoi int)


returns text as
'
declare
studinfo student%rowtype;
begin
select * into studinfo from student where
sno=snoi;
return studinfo;
end;
' language 'plpgsql';
Record Variable

 A record variable is similar to a row-type variable. It can hold only one row of a result set.
 Unlike a row-type variable, a record variable does not have a predefined structure. The
structure of a record variable is determined according to select statement
Syntax :

Record_variable record ;

Student (rno,name,class,div)
1. Declare a variable that can hold record of name and class of student

studrec record ;
//Example of record type variable

4. Create a function to display name and class of student for roll no 1


create or replace function studrec() returns text as
'
declare
studrec record;
begin
select sname, class into studrec from student where
sno=1;
return studrec;
end;
' language 'plpgsql';
Emp ( eno,ename,salary,bdate,dno)

Department (dno,dname,dloc)

1. Write a function to display information of employee for given eno.

2. Write a function to display ename and salary for a given eno

3. Write a function to display dname and location in which eno 2 is working


Employee (eno,ename,salary,joindate,age,city)
Project (pno,pname,ptype,startdate,budget)
Project and emp are related with many to many relationships with descriptive attribute
n_of_hours
Using Project-Employee database
a) Write a function which accepts project name as input and returns the number of employees
working on the project.
b) Write a function to find the number of employees whose date of joining is before
‘’03/10/2010’’
c) Write a function to display number of projects started on given date
d) Write a function to display pname and project type for given pno.
e) Write a function which accepts project number and returns information of project
IF statement

The if statement executes a command based on a specific condition.


If statement determines which statements to execute based on the result
of a boolean expression
1. Syntax of IF statement

if condition then
statements;
end if;
Write a function to display name of student for given rollno. If given rollno is not
present in table then display message invalid rollno
create or replace function sturno(rno int) returns
varchar(20) as
'
declare
stud_name varchar(20);
begin
select sname into stud_name from student where sno=rno;
if not found then
raise notice ‘’ the Roll No % is invalid ‘’,rno;
end if ;
return stud_name;
end;
' language 'plpgsql';
IF THEN ELSE statement

 The if then else statement executes the statements in the if branch if the condition evaluates to true; otherwise, it
executes the statements in the else branch.

2. If then else

if condition then
statements;
else
alternative-statements;
end if;
Write a function to display name of student for given rollno. If given rollno is not
present in table then display message invalid rollno else display name of student

create or replace function sturnou(rno int) returns


void as
'
declare
stud_name varchar(20);
begin
select sname into stud_name from student where
sno=rno;
if not found then
raise notice ‘’ the Roll No % is invalid‘’,rno;
else
raise notice ''student name is %'',stud_name;
end if ;
end;
' language 'plpgsql';
Consider relation , Employee (eno,ename,salary,city)

Write a function to accept eno from user and display its city. If
employee is not present in the table display
Message ‘ employee number % is not valid ‘

Write a function to accept eno from user. If eno is valid display


message containing employee name ,else display message eno is not
valid
IF THEN ELSIF statement
 The if and if then else statements evaluate one condition. However, the if then elsif statement evaluates multiple conditions.

2. If then elsif

if condition_1 then
statement_1;
elsif condition_2 then
statement_2;
...
elsif condition_n then
statement_n;
else
else-statement;
end if;
Write a function to accept rno and get the class .If class is FYBCA then display 'first year, if
SYBCA then display second year for SYBCA,third year for TYBCA invalid rno for wrong
output
create or replace function stuclass(rno int) returns
void as
'
declare
classn varchar(20);
begin
select class into classn from student where sno=rno;
if not found then
raise notice '' the Roll No % is invalid'',rno;
elsif classn=''FYBCA'' then
raise notice ''First year student'';
elsif classn=''SYBCA'' then
raise notice ''Second year student'';
elsif classn=''TYBCA'' then
raise notice ''Third year student'';
end if ;
end;
' language 'plpgsql';
While Loop

The while loop statement executes a block of code until a condition evaluates to false..

while condition
Loop
statements;
end loop;
create or replace function counter() returns
void as
'
declare
counter integer := 0;
begin
while counter < 5
loop
raise notice ‘'Counter value %'', counter;
counter := counter + 1;
end loop;
end;
' language 'plpgsql';
For Loop(iterate through a query result set)

For {record_variable | %rowtype_variable


} IN
select_statement
LOOP
Statement;
[……….]
END LOOP
// For Loop

Display names of students for given class

create function class_stud1(classi varchar(20)) returns


text as '
declare
stud_info text :=''\n'';
row_data student%Rowtype;
begin
for row_data in select * from student where class =
classi

Loop
stud_info := stud_info || row_data.sname || ''\n'';
end loop;
return stud_info;
end; ' language 'plpgsql';
// For Loop

Display names of students for given class

create or replace function class_stud2(classi


varchar(20)) returns void as '
declare

row_data student%Rowtype;
begin
for row_data in select * from student where class =
classi
Loop
raise notice '' % '',row_data;
end loop;

end; ' language 'plpgsql';


Functions to perform UPDATE operation

1) Student (sno,sname,class)

write a function to update class to SYBCA for given rno

create [or replace] function Create function classupdate(rollno


function_name() int) returns void as
returns void as ‘
begin Begin
Update statement Update student class=‘SYBCA’
end; where rno=rollno;
‘ language ‘plpgsql’ ; End

Functions to perform DELETE operation

1) Student (sno,sname,class)

write a function to delete information of students for given class

Create function(classi varchar(20)) returns


create [or replace] void as
function ‘
function_name() Begin
returns void as Delete from student where class=classi;
begin End
Delete statement ‘
end;
‘ language ‘plpgsql’ ;
Emp(eno,ename,salary,city)

Write a function to move all people living pune to


mumbai

1 Punam 100000 mumbai


2 Kalyani 50000 mumbai
3 Divya 700000 mumbai
4 nilima 60000 mumbai
Cursors
 Cursor allows you to encapsulate a query and process each
individual row at a time.
 you can develop a function that returns a reference to a
cursor. This is an effective way to return a large result set
from a function.
Steps to create a cursor
1.First, declare a cursor.
2.Next, open the cursor.
3.Then, fetch rows from the result set into a target.
4.After that, check if there is more row left to fetch. If
yes, go to step 3,
5.otherwise, go to step Finally, close the cursor.
Select sname,class from
student;
punam FYBCA
divya FYBCA
kalyani FYBCA
nilima FYBCA

Select sname from student


where class= ‘FYBCA’
Syntax to create use cursors
1. Declare a cursor

cursor_variable cursor for query

Ex. Student (rno,name,class,city)


Declare a cursor for information of students from pune city

Studinfo cursor for select * from students where city=‘pune’ ;

Declare a cursor for rno and name of FYBCA class .


Syntax to create use cursors
1. Declare a cursor

cursor_varible cursor for query

2. Opening cursors

OPEN cursor_variable ;

3. Fetch the cursor


FETCH cursor_variable into target_variable
4. Close the cursor

Close cursor_variable;
Write a stored function using cursors to accept a area name from the user
and to list all persons living in given area.
create or replace function pinfo(parea varchar(20)) returns void
as'
declare
percursor cursor for select * from person where aname=parea;
personinfo person%rowtype;

begin
open percursor;
loop
fetch percursor into personinfo;
exit when not found;
raise notice'' person information % % ‘’,personinfo;
end loop;
close percursor;
end;
'language 'plpgsql';
Write a stored function using cursors to accept a area name from the user
and to list pname and their income living in given area.
create or replace function pinfo1(parea varchar(20)) returns void
as'
declare
percursor cursor for select pname,income from person
where aname=parea;
pername varchar(20);
pincome float ;
begin
open percursor;
loop
fetch percursor into pername,pincome;
exit when not found;
raise notice'' person name is % and income is %
'',pername,pincome;
end loop;
close percursor;
Write a function using cursor to move all students of TYBCA to SYBCA
create or replace function updateclass() returns void
as'
declare
studcur cursor for select * from student where
class='‘TYBCA'';
begin
open studcur;
loop
move next from studcur;
exit when not found;
update student set class='‘SYBCA'';
end loop;
close studcur;
end;
'language 'plpgsql';
student (sno integer, s_name char(30), s_class char(10), s_addr
char(50))
teacher (tno integer, t_name char (20), qualification char
(15),experience integer)
Stud_teach(sno,tno,subject,marks)
1)Write a stored function using cursors, to accept a address from the
user and display information of students staying at given address.
create or replace function studinfo1(add varchar(20)) returns void as'
declare

cur1 cursor for select sname,subject from student,stud_teach where

student.sno=stud_teach.sno and address=add;


studname varchar(20);
sub varchar(20);

begin
open cur1;
loop
fetch cur1 into studname,sub;
exit when not found;
raise notice ''sname % and subject name % '',studname,sub;
end loop;
close cur1;
end;
'language 'plpgsql';
Write a stored function using cursors which will calculate total and percentage of each student

create or replace function studper() returns void as'


declare
cur1 cursor for select sno,sum(marks),avg(marks) from
stud_teach group by sno;
sno1 int;
sum int;
avg numeric;
begin
open cur1;
loop
fetch cur1 into sno1,sum,avg;
exit when not found;
raise notice ''sno % and sum(marks) % and avg
%'',sno1,sum,avg;
end loop;
close cur1;
end;
Write a stored function using cursors which will
calculate total and percentage of each student.

student (sno integer, s_name char(30), s_class char(10), s_addr


char(50))
teacher (tno integer, t_name char (20), qualification char
(15),experience integer)
Stud_teach(sno,tno,subject,marks)

cur1 cursor for select sno,sum(marks),avg(marks)


from stud_teach group by sno;
Trigger
 trigger is a stored program
invoked automatically in
response to an event such as
insert, update, or delete that
occurs in the associated
table.

For example, you can define


a trigger that is invoked
automatically before a new
row is inserted into a table.
Delete 1) Keep watch for delete operation on table
2) perform task : display message that student information is
removed

Insert 1) keep watch on insert operation on table


2) perform task : check class is SYBCA or FYBCA. Insert operation will
not execute if class is not FYBCA and SYBCA

Update 1) keep watch : insert or update


2) perform task :check account balance should be at least 10000.
operation should be denied else
A trigger is a PL/pgSQL block that is associated with a
table, stored in a database and executed in response to
a specific data manipulation event.
Triggers can be executed or fired in response to the following
events.

a. A row is inserted into table


b. A row in a table is updated.
c. A row in a table is deleted.
Syntax for creating Triggers in mysql

CREATE TRIGGER trigger_name


trigger_event
ON tbl_name FOR EACH ROW execute procedure
functionname ( arguments) ;

Define trigger
User defined function
Trigger event can be
Create a BEFORE INSERT trigger : if you want to
verify data before it is inserted into table . 
Create an AFTER INSERT trigger  :

Create a BEFORE UPDATE trigger


Create an AFTER UPDATE trigger 

Create a BEFORE DELETE trigger

Create an AFTER DELETE trigger 


Example : consider table student(rno,name,marks,class)

Write a trigger after deleting a student record from the student table. Raise a notice
and display the message “student record is being deleted”

create or replace function studdelete( )


returns trigger as'
begin
raise notice'‘student record of is
being deleted'‘,;
return old;
end;
‘ language 'plpgsql';
create trigger deletetrigger
after delete on student for
each row execute procedure
studdelete();
student (sno integer, s_name char(30), s_class char(10), s_addr char(50))
teacher (tno integer, t_name char (20), qualification char
(15),experience integer)
Stud_teach(sno,tno,subject,marks)

1. Write a trigger which will fire before insert on the student table which check that the rollno
must be less than 120
create or replace function checkroll( ) returns trigger as'
begin
if (new.sno>120) then
raise exception '' roll number should be less than
120 '';
end if ;
return new;
end;
'language 'plpgsql';

create trigger insertriger before insert on student


for each row execute procedure checkroll();
In the above example, there is new keyword 'NEW' which is a PLSQL extension
to triggers. There is two PLSQL extension to triggers 'OLD' and 'NEW'. OLD and
NEW are not case sensitive.

Within the trigger body, the OLD and NEW keywords enable you to access
columns in the rows affected by a trigger
In an INSERT trigger, only NEW.col_name can be used.

In a UPDATE trigger, you can use OLD.col_name to refer to the columns of a
row before it
is updated and NEW.col_name to refer to the columns of the row after it is
updated.

In a DELETE trigger, only OLD.col_name can be used; there is no new row.
Exception Handling
 The RAISE statements raise errors and exceptions during a PL/pgSQL function’s
execution. A Raise statement is also given the level of error it should raise and the string
error message it should send to postgreSQL.
 The string can also be embedded with variables and expressions, that one needs to list along with the error message.
 The percent (%) sign is used as the place holder for the variables that are inserted into the string.

NOTICE
Notice level statements send the specified text as a Notice;

EXCEPTION
Exception level statements send the specified text as an
ERROR. The exception level also causes the current
transaction to be aborted.
Emp(eno, ename , designation, sal,dno)
Dept(dno, dname, dloc)

eno ename Designation sal dno


dno dname dloc 11 punam Professor 100000 6
6 finance 101 22 Divya Professor 100000 2
2 HR 102 33 Nilima Lecturer 50000 6
3 Admin 103 44 Smita Lecturer 60000 3
student (sno integer, s_name char(30), s_class char(10), s_addr char(50))
teacher (tno integer, t_name char (20), qualification char
(15),experience integer)
Stud_teach(sno,tno,subject,marks)

2. Write a trigger which will fire before update on stud_teach . New value marks should be greater than or equal
to previous marks

create or replace function checkmarks( ) returns trigger as'


begin
if (new.marks < old.marks) then
raise exception '' marks can not be reduced '';
end if ;
return old;
end;
'language 'plpgsql';

create trigger insertriger before insert on student


for each row execute procedure checkroll();

You might also like