Unit 9 PL-SQL Concepts
Unit 9 PL-SQL Concepts
Page| 1
L.J Institutes of Engineering and Technology
Semester: II Subject Database Management System
Unit-9 PL/SQL Concepts
Note that you can use either := or = assignment operator to initialize and assign a
value to a variable.
do $$
declare
counter integer := 1;
first_name varchar(50) := 'John';
last_name varchar(50) := 'Doe';
payment numeric(11,2) := 20.5;
begin
raise notice '% % % has been paid % USD',counter,
first_name, last_name, payment;
end $$;
➢ Copying data types
• The %type provides the data type of a table column or another variable. Typically,
you use the %type to declare a variable that holds a value from the database or
another variable.
• The following illustrates how to declare a variable with the data type of a table
column:
variable_name table_name.column_name%type;
➢ PL/pgSQL Row Types
• To store the whole row of a result set returned by the select into statement, you use
the row-type variable or row variable.
row_variable table_name%ROWTYPE;
row_variable view_name%ROWTYPE;
• To access the individual field of the row variable, you use the dot notation (.) like
this:
row_variable.field_name
PostgreSQL SELECT INTO Statement
• The select into statement allows you to select data from the database and assign the
data to a variable.
Syntax:
SELECT select_list INTO variable_name FROM table_name
WHERE condition;
• In this syntax, you place the variable after the into keyword. The select into statement
will assign the data returned by the select clause to the variable.
• Besides selecting data from a table, you can use other clauses of the select statement
such as join, group by, and having.
Page| 4
L.J Institutes of Engineering and Technology
Semester: II Subject Database Management System
Unit-9 PL/SQL Concepts
Page| 5
L.J Institutes of Engineering and Technology
Semester: II Subject Database Management System
Unit-9 PL/SQL Concepts
Control Structures
PL/pgSQL IF Statement
• The IF statement determines which statements to execute based on the result of a
Boolean expression. PL/pgSQL provides you with three forms of the IF statements.
• IF THEN
• IF THEN ELSE
• IF THEN ELSIF
Page| 6
L.J Institutes of Engineering and Technology
Semester: II Subject Database Management System
Unit-9 PL/SQL Concepts
Page| 8
L.J Institutes of Engineering and Technology
Semester: II Subject Database Management System
Unit-9 PL/SQL Concepts
if a=30 then
update public.student set name = n;
raise notice 'updation done';
else
raise notice 'updation not possible';
end if;
end;
Select * from student;
Page| 11
L.J Institutes of Engineering and Technology
Semester: II Subject Database Management System
Unit-9 PL/SQL Concepts
Page| 12
L.J Institutes of Engineering and Technology
Semester: II Subject Database Management System
Unit-9 PL/SQL Concepts
Page| 13
L.J Institutes of Engineering and Technology
Semester: II Subject Database Management System
Unit-9 PL/SQL Concepts
1. Implicit cursors
• Implicit cursors are automatically created by PL/pgSQL 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/pgSQL, you can refer to the most recent implicit cursor as the SQL cursor,
which always has attributes such as FOUND, NOT FOUND, and ROW_COUNT.
Attribute Description
FOUND Its return value is TRUE if DML statements like INSERT, DELETE
and UPDATE affect at least one row or more rows or a SELECT
INTO statement returned one or more rows. Otherwise, it returns
FALSE.
NOTFOUND Its return value is TRUE if DML statements like INSERT, DELETE
and UPDATE affect no row, or a SELECT INTO statement return
no rows. Otherwise, it returns FALSE. It is a just opposite of
FOUND.
ROW_COUNT It returns the number of rows affected by DML statements like
INSERT, DELETE, and UPDATE or returned by a SELECT INTO
statement.
Note: Above mentioned attributes are used with explicit cursor also.
Example
CREATE TABLE Employee
(id int, name varchar (20), age int);
INSERT INTO Employee VALUES
(1, 'Jay', 60), (2, 'Ajay', 35),
(3, 'Vijay', 40);
Do $$
declare
row_counter int;
begin
Delete from Employee where age>50;
if found then
get diagnostics row_counter=row_count;
raise notice 'deleted rows are %',row_counter;
end if;
end;
$$
Page| 14
L.J Institutes of Engineering and Technology
Semester: II Subject Database Management System
Unit-9 PL/SQL Concepts
2. Explicit Cursors
• The Explicit cursors are defined by the programmers to gain more control over the
context area.
• These cursors should be defined in the declaration section of the PL/pgSQL block.
• It is created on a SELECT statement which returns more than one row.
➢ Steps:
• You must follow these steps while working with an explicit cursor.
Step 1:
• Declare the cursor to initialize in the memory.
Step 2:
• Open the cursor to allocate memory.
Step 3:
• Fetch the cursor to retrieve data.
Step 4:
• Close the cursor to release allocated memory.
Example 1 To fetch record of column id, name & address into cursor & also display
the same.
create table t1 (id integer,
name varchar (10), age int,
address varchar (100), salary int);
insert into t1
values (1,'ram',30,'abad',25000);
Do $$
declare
c1_id t1.id%type;
c1_name t1.name%type;
c1_address t1.address%type;
t1_cursor cursor for select id,name, address from t1;
begin
open t1_cursor;
loop
Page| 15
L.J Institutes of Engineering and Technology
Semester: II Subject Database Management System
Unit-9 PL/SQL Concepts
Page| 16
L.J Institutes of Engineering and Technology
Semester: II Subject Database Management System
Unit-9 PL/SQL Concepts
Page| 17
L.J Institutes of Engineering and Technology
Semester: II Subject Database Management System
Unit-9 PL/SQL Concepts
Stored Function
• The create function statement allows you to define a new user-defined function.
Syntax:
CREATE[or replace]FUNCTION function_name(parameter_list)
RETURNS return_datatype
language plpgsql
as
$$
declare
-- variable declaration
begin
-- logic
end;
$$
In this syntax:
• First, specify the name of the function after the create function keywords. If you want
to replace the existing function, you can use the or replace keywords.
• Then, specify the function parameter list surrounded by parentheses after the function
name. A function can have zero or many parameters.
• Next, specify the datatype of the returned value after the returns keyword.
• After that, use the language plpgsql to specify the procedural language of the function.
Note that PostgreSQL supports many procedural languages, not just plpgsql.
• Finally, place a block in the dollar-quoted string constant.
Example 1 Creates a function that counts the films whose length between
the len_from and len_to parameters (refer dvdrental)
CREATE or replace FUNCTION get_film_count
(len_from int, len_to int)
RETURNS integer
language plpgsql
as
$$
declare
film_count integer;
begin
SELECT count(*) INTO film_count FROM film
WHERE length BETWEEN len_from AND len_to;
return film_count;
end;
$$;
Page| 18
L.J Institutes of Engineering and Technology
Semester: II Subject Database Management System
Unit-9 PL/SQL Concepts
Example 2 Find out minimum value out of given two values using function:
create or replace function min (x int, y int)
returns integer as
$$ To call Function:
Declare Select min (5,3);
z integer;
begin
if x<y then
z:=x;
else
z:=y;
end if;
return z;
end;
$$
language plpgsql;
Page| 20
L.J Institutes of Engineering and Technology
Semester: II Subject Database Management System
Unit-9 PL/SQL Concepts
Example 3 Create function using PL/pgSQL to change salary from 25000 to 30000
whose emp id is 1.
Let initial table emp has following details:
Page| 21
L.J Institutes of Engineering and Technology
Semester: II Subject Database Management System
Unit-9 PL/SQL Concepts
Stored Procedure
• A drawback of user-defined functions is that they cannot execute transactions. In
other words, inside a user-defined function, you cannot start a transaction, and
commit or rollback it.
• To define a new stored procedure, you use the create procedure statement.
Syntax:
create [or replace] procedure procedure_name
(parameter_name [IN | INOUT] type [, ...])
language plpgsql
as $$
declare
-- variable declaration
begin
-- stored procedure body
end; $$
• In this syntax:
• First, specify the name of the stored procedure after the create
procedure keywords.
• Second, define parameters for the stored procedure. A stored procedure can accept
zero or more parameters.
• Third, specify plpgsql as the procedural language for the stored procedure. Note
that you can use other procedural languages for the stored procedure such as SQL,
C, etc.
• Finally, use the dollar-quoted string constant syntax to define the body of the
stored procedure.
• Parameters in stored procedures can have the in and inout modes. They cannot
have the out mode.
• A stored procedure does not return a value. You cannot use the return statement with
a value inside a store procedure
• However, you can use the return statement without the expression to stop the stored
procedure immediately:
➢ Calling a stored procedure
• To call a stored procedure, you use the CALL statement as follows:
CALL stored_procedure_name(argument_list);
➢ Drop Procedure statement
The drop procedure statement removes a stored procedure. The following illustrates the syntax of the
drop procedure statement:
DROP PROCEDURE procedure-name;
Page| 22
L.J Institutes of Engineering and Technology
Semester: II Subject Database Management System
Unit-9 PL/SQL Concepts
Page| 23
L.J Institutes of Engineering and Technology
Semester: II Subject Database Management System
Unit-9 PL/SQL Concepts
end;
$$
language plpgsql;
Output: CALL get_emp_detail(1);
Example 3 Code for increasing salary by 10 % of employee whose age is 25.
create or replace procedure increment (a in int) as $$
declare
emp_name emp.ename%type;
emp_sal emp.salary%type;
newsalary int;
Begin
SELECT ename,salary INTO emp_name,emp_sal FROM emp
WHERE age=a;
newsalary:=emp_sal+0.1*emp_sal;
UPDATE emp SET salary=newsalary WHERE age=a;
raise notice 'newsalary:%',newsalary;
end;
$$
language plpgsql;
Output: CALL increment (25);
Database Triggers
• A PostgreSQL trigger is a function invoked automatically whenever an event
associated with a table occurs.
• A trigger is a special user-defined function associated with a table.
• To create a new trigger, you define a trigger function first, and then bind this trigger
function to a table.
• Triggers are stored programs, which are automatically executed or fired when some
event occurs.
• The difference between a trigger and a user-defined function is that a trigger is
automatically invoked when a triggering event occurs.
➢ A trigger is executed due to the following circumstances listed below:
1. By a DDL (Data Definition Language) statement like DROP, ALTER, or
CREATE.
2. By a DML (Data Manipulation Language) statement like UPDATE, INSERT, or
DELETE.
3. By a database action like SHUTDOWN, STARTUP, LOGOFF, and LOGON.
• A trigger can be set on a schema, view, or database that has an event attached.
Page| 24
L.J Institutes of Engineering and Technology
Semester: II Subject Database Management System
Unit-9 PL/SQL Concepts
➢ Advantages of Triggers
• 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
➢ Usages of Triggers
• Prevents improper transactions.
• Accumulates information on table usage.
• Monitor critical information.
➢ Types of Triggers In PL/pgSQL
• The triggers can be categorized based on parameters. Types are listed below:
1) Categorization on the trigger level.
1. ROW Level trigger: It gets executed for each record that got updated by a DML
statement.
2. STATEMENT Level trigger: It gets executed only once by the event statement.
2) Categorization of the trigger timing.
1. BEFORE trigger: It gets executed prior to the specific event that has taken place.
2. AFTER trigger: It gets executed post the specific event that has taken place.
3) Categorization of the trigger event.
1. DML trigger: It gets executed if a DML event like an UPDATE, INSERT, or
DELETE is performed.
2. DDL trigger: It gets executed if a DDL event like a DROP, ALTER, or CREATE
is performed.
3. DATABASE trigger: It gets executed if a database event like SHUTDOWN,
STARTUP, LOGOFF, and LOGON has taken place.
Note: Unlike other databases, a trigger is broken into two pieces
1. Trigger
2. Trigger Function
Page| 25
L.J Institutes of Engineering and Technology
Semester: II Subject Database Management System
Unit-9 PL/SQL Concepts
Page| 26
L.J Institutes of Engineering and Technology
Semester: II Subject Database Management System
Unit-9 PL/SQL Concepts
Example 1 Write a trigger for insertion of a row into a person table. On firing the
trigger, operation should be displayed.
or
Page| 27
L.J Institutes of Engineering and Technology
Semester: II Subject Database Management System
Unit-9 PL/SQL Concepts
399. Write A PL/SQL block to print the sum of Numbers from 1 to 50.
do $$
declare
a int;
sum int :=0;
begin
for a in 1..50 loop
sum = sum + a;
end loop;
raise notice 'sum = %', sum;
end;
$$
400. Write A PL/SQL block to print the given number is Odd or Even
do $$
declare
a int :=5;
begin
if mod (a,2)=0 then
raise notice 'even';
else
raise notice 'odd';
end if;
end;
$$
401.Write a PL/SQL cursor to increase the salary by 10% for the employees having
salary less then 700000.
Do $$
DECLARE
cur CURSOR FOR SELECT employee_id, salary FROM employees
WHERE salary < 70000;
C1 employee.employee_id%TYPE;
C2 employee.salary%TYPE;
BEGIN
OPEN cur;
LOOP
FETCH cur INTO C1,C2;
EXIT WHEN NOT FOUND;
UPDATE employees SET salary = salary + (0.1* salary)
WHERE current of cur;
END LOOP;
CLOSE cur;
END;
$$
Page| 29
L.J Institutes of Engineering and Technology
Semester: II Subject Database Management System
Unit-9 PL/SQL Concepts
402. Write a PL/SQL cursor to display the names and branch of all students from
the STUDENT relation.
do $$
declare
c1_name std.name%type;
c2_branch std.branch%type;
s_cursor cursor for select name,branch from std;
begin
open s_cursor;
loop
fetch s_cursor into c1_name,c2_branch;
exit when not found;
raise notice 'name:%,branch: %',c1_name,c2_branch;
end loop;
close s_cursor;
end;
$$
403. Write a PL/SQL block using explicit cursor that will display the customer
name, the fixed deposit number and the fixed deposit amount of the first 5
customers holding the highest amount in fixed deposits.
Use following database:
cust_mstr ( custno, name, occupation)
fd_dtls ( fd_ser_no, custno, fd_no, type, period, opndt, duedt, amt, dueamt)
acct_fd_cust_dtls ( acct_fd_no, custno)
do $$
declare
c1_cust_no cust_mstr.custno%type;
c2_name cust_mstr.name%type;
c3_fd_no fd_dtls.fd_no%type;
c4_amount fd_dtls.amt%type;
c_cursor cursor for select name,fd_no,amt from
cust_mstr,fd_dtls where cust_mstr.custno =
fd_dtls.custno order by amt desc limit 5;
begin
open c_cursor;
loop
fetch c_cursor into c2_name, c3_fd_no, c4_amount;
exit when not found;
raise notice 'name:%,fd_no:%,amount:%',
c2_name,c3_fd_no,c4_amount;
end loop;
close c_cursor;
end;
$$
Page| 30
L.J Institutes of Engineering and Technology
Semester: II Subject Database Management System
Unit-9 PL/SQL Concepts
411. Write PL/SQL code block to increment the employee’s salary by 1000 whose
employee id is 102 from the given table below. Schema emp1 (eid, salary)
do $$
declare
c1_eid emp1.eid%type;
begin
c1_eid := 1;
if c1_eid = 1 then
update emp1 set salary = salary +1000 where eid=1;
end if;
raise notice 'updated';
end;
$$
412. Write a PL/SQL code to find whether a given string is palindrome or not.
do $$
declare
string text := 'bob';
reverse_string text;
begin
reverse_string := reverse (string);
if string = reverse_string then
raise notice 'The string is Palindrome';
else
raise notice 'The string is not Palindrome';
end if;
end; $$
414. Write PL/SQL program to find the sum of digits of a number.
do $$
declare
a int :=123;
sum int := 0;
digit int;
begin
while a <> 0 loop
digit = mod (a,10);
sum = sum + digit;
a := (a/10);
end loop;
raise notice 'ans:%',sum;
end; $$
Page| 33