Chapter 1 Part 2 Advanced SQL
Chapter 1 Part 2 Advanced SQL
Prerequisite
Students should able to solve simple ,nested and queries using
joins
Emp(eno, ename , designation, sal,dno)
Dept(dno, dname, dloc)
Project
Example :
Teacher(tno,tname,qualification,exp)
2. Create a view containing the project name, project type and start date of the
project
b. List the name and type of projects started on 1st April 2014.
1. Create a view containing details of all the teachers teaching the subject
‘Mathematics’.
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
2. Create a view containing the project name, project type and start date of the project
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.
-- 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
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)
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
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.
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;
Studinfo student%rowtype;
2. Student (rno,name,class)
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
Department (dno,dname,dloc)
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
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 ‘
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)
Loop
stud_info := stud_info || row_data.sname || ''\n'';
end loop;
return stud_info;
end; ' language 'plpgsql';
// For Loop
row_data student%Rowtype;
begin
for row_data in select * from student where class =
classi
Loop
raise notice '' % '',row_data;
end loop;
1) Student (sno,sname,class)
1) Student (sno,sname,class)
2. Opening cursors
OPEN cursor_variable ;
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
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
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 :
Write a trigger after deleting a student record from the student table. Raise a notice
and display the message “student record is being deleted”
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';
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)
2. Write a trigger which will fire before update on stud_teach . New value marks should be greater than or equal
to previous marks