You are on page 1of 10

Copyright © austinmakasare22@gmail.

com

DBMS stored Function, Cursor & Trigger

The basic syntax to create a function is as follows −


CREATE [OR REPLACE] FUNCTION function_name (arguments)
RETURNS return_datatype AS $variable_name$
DECLARE
declaration;
[...]
BEGIN
< function_body >
[...]
RETURN {variable_name | value}
END; LANGUAGE plpgsql;
Where,
• function-name specifies the name of the function.
• [OR REPLACE] option allows modifying an existing function.
• Arguments can be type like IN, OUT, INOUT and VARIADIC.

• IN: It is the input parameter. It is used to insert the data from the procedure
into the table.
• OUT: It is the output parameter. It is used to return the value.
• INOUT: It represents both input and output parameters. As they can pass
and returns the value.
• VARIADIC: A PostgreSQL function can accept a variable number of
arguments with one condition have the same data type.
• The function must contain a return statement.
• RETURN clause specifies that data type you are going to return from the function.
The return_datatype can be a base, composite, or domain type, or can reference the
type of a table column.
• function-body contains the executable part.
• The AS keyword is used for creating a standalone function.
• plpgsql is the name of the language that the function is implemented in. Here, we
use this option for PostgreSQL, it Can be SQL, C, internal, or the name of a user
defined procedural language. For backward compatibility, the name can be enclosed
by single quotes.

Example:

Copyright © austinmakasare22@gmail.com
Copyright © austinmakasare22@gmail.com

Create or replace function hi_lo (IN a numeric, IN b numeric, IN c numeric, OUT hi numeric,
OUT lo numeric) AS’ BEGIN
hi := GREATEST(a,b,c); lo
:= LEAST(a,b,c);
END;
‘Language ‘plpgsql’;

Calling a function:

The syntax for calling PL/pgSQL function is

1. SELECT fuction_name(arguments);
2. Variable_identifier: = fuction_name(arguments);
e.g postgres=# SELECT hi_lo(10,20,30);
o/p : 30,10

We can also use the PERFORM keyword to call a function and ignore its
return data.
3. PERFORM fuction_name(arguments);

Dropping a function
drop function [if exists] function_name(argument_list)
[cascade | restrict]
Type: The data type(s) of the function’s arguments.
CASCADE: Automatically drop objects that depend on the function (such as operators or
triggers).
RESTRICT: Refuse to drop the function if any objects depend on it.

e.g drop function hi_lo();

Difference between Stored function and Stored Procedure

Stored function Stored Procedure


Functions are not used for any kind of The purpose to use procedure is to
updating because functions are not modify the database data where
allowed to change anything in the return value is not required like
database, is only used for plain delete, update, drop etc.
queries.

Copyright © austinmakasare22@gmail.com
Copyright © austinmakasare22@gmail.com

Functions should contain at least one Stored procedure neither contain any
parameter and should return value. parameter nor return any value.
Functions are created with the CREATE Procedures are created with the
FUNCTION command. CREATE PROCEDURE
We cannot call stored procedures We can call functions from stored
from functions. procedures.
Functions can have only input Procedures can have input or output
parameters for it. parameters.
Transactions are not allowed with Transactions can be executed from
functions. stored procedure also it can use
commit and rollback inside procedure.

Handling Errors and Exceptions

Error and Exceptions handling is important thing in any programming language.


Error is an illegal operation performed by the user which results in abnormal
working of the program.

An exception is an event which occurs during the execution of a program that


disrupts the normal flow of the program’s instructions. The RAISE statement is
used to raise errors and exceptions during a PL/pgSQL function’s operation.

Syntax:

RAISE level ‘ ‘format string’ ‘[,identifier[.....] ];

Or
RAISE level format;
Following the RAISE statement is the level option that specifies the error severity.
PostgreSQL provides the following levels:
• DEBUG
• LOG
• NOTICE
• INFO
• WARNING
• EXCEPTION

The format is a string that specifies the message. The format uses percentage ( %)
placeholders that will be substituted by the next arguments. The number of
Copyright © austinmakasare22@gmail.com
Copyright © austinmakasare22@gmail.com

placeholders must match the number of arguments, otherwise, PostgreSQL will


report error message.

CREATE FUNCTION raise_test () RETURNS integer AS '


DECLARE

cnt INTEGER = 1;

BEGIN

RAISE DEBUG ''The raise_test () function began.'';

cnt = cnt + 1;
RAISE NOTICE ''Variable an integer was changed.'';
RAISE NOTICE ''Variable an integer’s value is now %.'‘, cnt;
RAISE EXCEPTION ''Variable % changed. Transaction aborted. ‘cnt;

RETURN 1;
END;
' LANGUAGE 'plpgsql';

Raising Errors:
To raise errors, you use the EXCEPTION level after the RAISE statement. Note that
the RAISE statement uses the EXCEPTION level by default. Besides raising an error,
you can add more detailed information by using the following clause with the
RAISE statement:
USING option = expression
The options can be any one of the below:
• MESSAGE: set error message text
• HINT: provide the hint message so that the root cause of the error is easier to be
discovered.
• DETAIL: give detailed information about the error.
• ERRCODE: identify the error code, which can be either by condition name or
directly five-character SQLSTATE code.
Example 1: DO
$$
DECLARE
email varchar (255) := 'raju@geeksforgeeks.org';

Copyright © austinmakasare22@gmail.com
Copyright © austinmakasare22@gmail.com

BEGIN
-- check email for duplicate
-- ...
-- report duplicate email
RAISE EXCEPTION 'Duplicate email: %', email
USING HINT = 'Check the email again';
END $$;

System defined (Internal) exceptions are raised automatically by the


runtime system. User defined exception should be raise. Syntax:
Declare
< Declaration Section>
Begin
<Statements>
Exception
When condition Then
Handler statements
End;

Cursors:
A Cursor in PostgreSQL is used to process large tables. Suppose if a table has 10
million or billion rows. While performing a SELECT operation on the table it will
take some time to process the result and most likely give an “out of memory”
error and the program will be terminated.
A Cursor can only be declared inside a transaction. The cursor does not
calculate the data but only prepares the query so that your data can be created
when FETCH is called. In the end, simply commit the transaction.
Cursor can be two types.
1. Implicit cursors are declared and managed by pl/pgsql for all DML and
PL/pgsql select statement
2. Explicit cursors are declared and managed by the programmer.
Explicit cursors operations are as follows.
1.First, declare a cursor.
2.Next, open the cursor.
Copyright © austinmakasare22@gmail.com
Copyright © austinmakasare22@gmail.com

3.Then, fetch rows from the result set into a target.


4.After that, check if there are more rows left to fetch. If yes, go to step 3,
otherwise go to step 5.
5.Finally, close the cursor.

1.Declare the cursor variable

Syntax:
DECLARE
[cursor name] CURSOR FOR [query]
• Use DECLARE to declare a cursor
• [cursor name] – Give any name to the cursor
• [query] – Give a query to the cursor

2.Opening the cursor:


The open keyword is used to open a cursor in PostgreSQL. Below is the example
Syntax
Open [[ NO ] SCROLL } FOR query (any query);
Example
Open test_cursor for select * from employee where emp_id = 1;

3.Fetching Rows:
After declaring a cursor, we can get the data using FETCH. The FETCH gets the next
row(s) from the cursor. If no row found, then it returns NULL.
Syntax:
FETCH [direction (rows)] FROM [cursor_name];

where direction can be empty, number of rows you want or one of the
following valid directions for the cursor:
Copyright © austinmakasare22@gmail.com
Copyright © austinmakasare22@gmail.com

NEXT
PRIOR
FIRST
LAST
ABSOLUTE count
RELATIVE count
count ALL
FORWARD BACKWARD

e.g FETCH curs1 INTO row1;


FETCH LAST FROM cur3 INTO title,release_year;

4.closing cursors

To close an opening cursor, we can use CLOSE statement. The Syntax is as


follows:
CLOSE cursor variable; e.g
CLOSE cur2;
The CLOSE statement releases resources or frees up cursor variable.

Advantage using cursors:


1.cusors are a useful tool if you don’t want to always execute the query and
wait for the full result set before returning from function.
2.Currently, cursors are also the only way to return multiple result sets out of
user defined function.
Disadvantage using cursor:
1.cusors mainly work to pass data between functions on the server, and you
are still limited to one record set per call returned to the database client.
2.cursors are sometimes confusing to use.

Copyright © austinmakasare22@gmail.com
Copyright © austinmakasare22@gmail.com

Trigger
A PostgreSQL trigger is a function invoked automatically whenever an event
associated with a table occurs. An event could be any of the following:
INSERT, UPDATE, DELETE or TRUNCATE.

A trigger is a special user-defined function associated with a table. To create a


new trigger, you must define a trigger function first, and then bind this trigger
function to a table. The difference between a trigger and a user-defined
function is that a trigger is automatically invoked when an event occurs.
PostgreSQL provides two main types of triggers:
1. Row level-triggers
2. Statement-level triggers

The differences between the two kinds are how many times the trigger is
invoked and at what time. For example, if you issue an UPDATE statement that
affects 20 rows, the row-level trigger will be invoked 20 times, while the
statement level trigger will be invoked 1 time.
You can specify whether the trigger is invoked before or after an event. If the
trigger is invoked before an event, it can skip the operation for the current row
or even change the row being updated or inserted. In case the trigger is
invoked after the event, all changes are available to the trigger.
Create Trigger:

To create a new trigger in PostgreSQL, you follow these steps:


• First, create a trigger function using CREATE FUNCTION statement.
• Second, bind the trigger function to a table by using the CREATE TRIGGER
statement.
Syntax:
CREATE FUNCTION trigger function ()
RETURNS trigger AS

To create a trigger, we use the CREATE TRIGGER function. Here is


the syntax for the function:
CREATE TRIGGER trigger-name [BEFORE|AFTER|INSTEAD OF] event
name ON table-name
Copyright © austinmakasare22@gmail.com
Copyright © austinmakasare22@gmail.com

[
-- Trigger logic
Execute PROCEDURE trigger function
];
The trigger-name is the name of the trigger.
The BEFORE, AFTER and INSTEAD OF are keywords that determine
when the trigger will be invoked.
The event-name is the name of the event that will cause the trigger
to be invoked. This can be INSERT, UPDATE, DELETE, etc.

List Trigger
All triggers that you create in PostgreSQL are stored in the pg_trigger table. To see
the list of triggers that you have on the database, query the table by running the
SELECT command as shown below:

SELECT * FROM pg_trigger

Drop Trigger
In PostgreSQL, the DROP TRIGGER statement is used to drop a trigger from a table.
Syntax:
DROP TRIGGER [IF EXISTS] trigger_name
ON table_name [ CASCADE | RESTRICT];

The trigger-name parameter denotes the name of the trigger that is to be


deleted.

The table-name denotes the name of the table from which the trigger is to be
deleted.

The IF EXISTS clause attempts to delete a trigger that exists. If you attempt to
delete a trigger that does not exist without using the IF EXISTS clause, you will get
an error.

The CASCADE option will help you to drop all objects that depend on the trigger
automatically.

Copyright © austinmakasare22@gmail.com
Copyright © austinmakasare22@gmail.com

If you use the RESTRICT option, the trigger will not be deleted if objects are
depending on it.

Advantage of Trigger

1. Triggers provide an alternative way to check the integrity of data.


2. Triggers can catch errors in business logic in the database layer.
3. Triggers are very useful to audit the changes of data in tables.

Disadvantage of Trigger:

1.Triggers are invoked and executed invisible from the client applications
therefore it is difficult to figure out what happen in the database layer

2.Triggers may increase the overhead of the database server.

Copyright © austinmakasare22@gmail.com

You might also like