5. FUNCTIONS (1/18)
● What is a Function?
A Function is a set of sql statements which aim to
accomplish the same task.
How is a function different from a procedure?
✔ A Function is more clear, organized and structured.
✔ It is easy to modify.
✔ It is easy to handle return values than in procedures. In
procedures, a temporary table might be necessary to carry
a return value and join it with an existing table. This
becomes unnecessary if functions are used instead.
PostgreSQL Statements 5
6. FUNCTIONS (2/18)
● CREATE FUNCTION - define a new function.
● DROP FUNCTION - remove a function.
● ALTER FUNCTION - change the definition of a
function.
PostgreSQL Statements 6
7. FUNCTIONS (3/18)
● CREATE FUNCTION - define a new function.
● Synopsis
CREATE FUNCTION name ( [ [ argmode ]
[ argname ] argtype [, …] ] )
RETURNS returntype
AS 'definition'
LANGUAGE 'langname'
● Create or Replace Function will either create a
new function, or replace an existing definition.
PostgreSQL Statements 7
8. FUNCTIONS (4/18)
● CREATE FUNCTION
Parameters
✔ Name: The name (optionally schema-qualified) of the
function to create.
✔ Argmode: The mode of an argument: either IN, OUT, or
INOUT. If omitted, the default is IN.
✔ Argname: The name of an argument.
✔ Argtype: The data type(s) of the function's arguments
(optionally schema-qualified), if any.
✔ Returntype: The return data type (optionally schema-
qualified).
PostgreSQL Statements 8
9. FUNCTIONS (5/18)
● CREATE FUNCTION
Parameters
✔ Langname: The name of the language that the function is
implemented in. May be SQL, C, internal, or the name of a
user-defined procedural language. For backward
compatibility, the name may be enclosed by single quotes.
✔ Definition: A string constant defining the function; the
meaning depends on the language. It may be an internal
function name, the path to an object file, an SQL command,
or text in a procedural language.
PostgreSQL Statements 9
10. FUNCTIONS (6/18)
● CREATE FUNCTION
Notice
✔ The name of the new function must not match any existing
function with the same argument types in the same
schema.
✔ However, functions of different argument types may share a
name (this is called overloading).
PostgreSQL Statements 10
11. FUNCTIONS (7/18)
● CREATE FUNCTION
Notice
✔ To update the definition of an existing function, use
CREATE OR REPLACE FUNCTION. It is not possible to
change the name or argument types of a function this way
(if you tried, you would actually be creating a new, distinct
function).
✔ Also, CREATE OR REPLACE FUNCTION will not let you
change the return type of an existing function. To do that,
you must drop and recreate the function.
PostgreSQL Statements 11
12. FUNCTIONS (8/18)
● CREATE FUNCTION
Notice
✔ If you drop and then recreate a function, the new function is
not the same entity as the old; you will have to drop existing
rules, views, triggers, etc. that refer to the old function.
✔ Use CREATE OR REPLACE FUNCTION to change a
function definition without breaking objects that refer to the
function.
PostgreSQL Statements 12
13. FUNCTIONS (9/18)
● CREATE FUNCTION
Example: Suppose we have a SQL statement:
INSERT INTO user VALUES(1,'Huỳnh Lê',21);
INSERT INTO user VALUES(2,'Văn Duy',23);
INSERT INTO user VALUES(3,'Đăng Huy',21);
INSERT INTO user VALUES(4,'Hồng Phúc',21);
PostgreSQL Statements 13
14. FUNCTIONS (10/18)
● CREATE FUNCTION
Example
✔ Create 1 function with name insert_user
CREATE OR REPLACE FUNCTION insert_user(id integer,
username character, age integer)
RETURNS void AS
$BODY$ BEGIN
INSERT INTO "user" (id,name,age) VALUES
(id,username,age);
END $BODY$
LANGUAGE plpgsql
PostgreSQL Statements 14
15. FUNCTIONS (11/18)
● CREATE FUNCTION
Example
✔ Use this function
SELECT insert_user(1, 'Huỳnh Lê', 21);
SELECT insert_user(2, 'Văn Duy', 23);
SELECT insert_user(3, 'Đăng Huy', 21);
SELECT insert_user(4, 'Hồng Phúc',21);
PostgreSQL Statements 15
16. FUNCTIONS (12/18)
● DROP FUNCTION - remove a function.
● Synopsis
DROP FUNCTION [ IF EXISTS ] name ( [ [ argmode ] [
argname ] argtype [, ...] ] ) [ CASCADE | RESTRICT ]
● Description
DROP FUNCTION removes the definition of an
existing function. To execute this command the user
must be the owner of the function. The argument
types to the function must be specified, since several
different functions may exist with the same name
and different argument lists.
PostgreSQL Statements 16
17. FUNCTIONS (13/18)
● DROP FUNCTION
Parameters
✔ IF EXISTS: Do not throw an error if the function does not
exist. A notice is issued in this case.
✔ Name: The name (optionally schema-qualified) of an
existing function.
✔ Argmode, argname, argtype: function's arguments
(optionally schema-qualified), if any.
✔ 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. This is the default.
PostgreSQL Statements 17
18. FUNCTIONS (14/18)
● DROP FUNCTION
Example
✔ This command removes the square root function
DROP FUNCTION sqrt(integer);
PostgreSQL Statements 18
19. FUNCTIONS (15/18)
● ALTER FUNCTION - change the definition of a
function
● Synopsis
ALTER FUNCTION name ( [ [ argmode ] [ argname ]
argtype [, ...] ] ) action [, ... ] [ RESTRICT ]
ALTER FUNCTION name ( [ [ argmode ] [ argname ]
argtype [, ...] ] ) RENAME TO new_name
ALTER FUNCTION name ( [ [ argmode ] [ argname ]
argtype [, ...] ] ) OWNER TO new_owner
PostgreSQL Statements 19
20. FUNCTIONS (16/18)
● ALTER FUNCTION
ALTER FUNCTION name ( [ [ argmode ] [ argname ]
argtype [, ...] ] ) SET SCHEMA new_schema
Notice
✔ You must own the function to use ALTER FUNCTION. To
change a function's schema, you must also have CREATE
privilege on the new schema. To alter the owner, you must
also be a direct or indirect member of the new owning role,
and that role must have CREATE privilege on the function's
schema.
PostgreSQL Statements 20
21. FUNCTIONS (17/18)
● ALTER FUNCTION
Parameters
✔ name: The name (optionally schema-qualified) of an
existing function.
✔ argmode, argname, argtype: function's arguments
(optionally schema-qualified), if any.
✔ new_name: The new name of the function.
✔ new_owner: The new owner of the function. Note that if the
function is marked SECURITY DEFINER, it will
subsequently execute as the new owner.
✔ new_schema: The new schema for the function.
PostgreSQL Statements 21
22. FUNCTIONS (18/18)
● ALTER FUNCTION
Examples
✔ To rename the function sqrt for type integer to square_root:
ALTER FUNCTION sqrt(integer) RENAME TO square_root;
✔ To change the owner of the function sqrt for type integer to
HuynhLe:
ALTER FUNCTION sqrt(integer) OWNER TO HuynhLe;
✔ To change the schema of the function sqrt for type integer
to maths:
ALTER FUNCTION sqrt(integer) SET SCHEMA maths;
PostgreSQL Statements 22
24. VIEWS (1/8)
● In SQL, a view is a virtual table based on the
result-set of an SQL statement.
● A view contains rows and columns, just like a
real table. The fields in a view are fields from
one or more real tables in the database.
● You can add SQL functions, WHERE, and JOIN
statements to a view and present the data as if
the data were coming from one single table.
PostgreSQL Statements 24
25. VIEWS (2/8)
● CREATE VIEW Syntax
CREATE [ OR REPLACE ] [ TEMP | TEMPORARY ] VIEW
name [ ( column_name [, ...] ) ] AS query
CREATE VIEW defines a view of a query. The view is not
physically materialized. Instead, the query is run every time
the view is referenced in a query.
CREATE OR REPLACE VIEW is similar, but if a view of the
same name already exists, it is replaced. You can only
replace a view with a new query that generates the identical
set of columns (i.e., same column names and data types).
PostgreSQL Statements 25
26. VIEWS (3/8)
● CREATE VIEW
Parameters
✔ TEMPORARY or TEMP: If specified, the view is created as
a temporary view. Temporary views are automatically
dropped at the end of the current session. Existing
permanent relations with the same name are not visible to
the current session while the temporary view exists, unless
they are referenced with schema-qualified names.
✔ Name: The name (optionally schema-qualified) of a view to
be created.
PostgreSQL Statements 26
27. VIEWS (4/8)
● CREATE VIEW
Parameters
✔ column_name: An optional list of names to be used for
columns of the view. If not given, the column names are
deduced from the query.
✔ Query: A query (that is, a SELECT statement) which will
provide the columns and rows of the view.
PostgreSQL Statements 27
28. VIEWS (5/8)
● CREATE VIEW
Examples: Create a view consisting of all comedy
films:
CREATE VIEW comedies AS
SELECT *
FROM films
WHERE kind = 'Comedy';
To use: SELECT * FROM comedies
PostgreSQL Statements 28
29. VIEWS (6/8)
● DROP VIEW — remove a view
● Synopsis
DROP VIEW name [, ...] [ CASCADE | RESTRICT
✔ DROP VIEW drops an existing view. To execute this
command you must be the owner of the view.
PostgreSQL Statements 29
30. VIEWS (7/8)
● DROP VIEW
Parameters
✔ Name: The name (optionally schema-qualified) of the view
to remove.
✔ CASCADE: Automatically drop objects that depend on the
view (such as other views).
✔ RESTRICT: Refuse to drop the view if any objects depend
on it. This is the default.
PostgreSQL Statements 30
31. VIEWS (8/8)
● DROP VIEW
Examples: This command will remove the view
called kinds:
✔ DROP VIEW kinds;
PostgreSQL Statements 31
33. TRIGGERS (1/11)
● A trigger is a specification that the database
should automatically execute a particular
function whenever a certain type of operation is
performed. Triggers can be defined to execute
either before or after any INSERT, UPDATE, or
DELETE operation, either once per modified
row, or once per SQL statement.
● If a trigger event occurs, the trigger's function is
called at the appropriate time to handle the
event.
PostgreSQL Statements 33
34. TRIGGERS (2/11)
● The trigger function must be defined before the
trigger itself can be created. The trigger function
must be declared as a function taking no
arguments and returning type trigger.
● Once a suitable trigger function has been
created, the trigger is established with CREATE
TRIGGER. The same trigger function can be
used for multiple triggers.
PostgreSQL Statements 34
35. TRIGGERS (3/11)
● CREATE TRIGGER
CREATE TRIGGER name { BEFORE | AFTER }
{ event [ OR ... ] }
ON table [ FOR [ EACH ] { ROW | STATEMENT } ]
EXECUTE PROCEDURE funcname ( arguments )
PostgreSQL Statements 35
36. TRIGGERS (4/11)
● CREATE TRIGGER
Parameters
✔ Name: The name to give the new trigger. This must be
distinct from the name of any other trigger for the same
table.
✔ Before/After: Determines whether the function is called
before or after the event.
✔ Event: One of INSERT, UPDATE, or DELETE; this specifies
the event that will fire the trigger. Multiple events can be
specified using OR.
✔ Table: The name (optionally schema-qualified) of the table
the trigger is for.
PostgreSQL Statements 36
37. TRIGGERS (5/11)
● CREATE TRIGGER
Parameters
✔ For each row / for each statement: This specifies whether
the trigger procedure should be fired once for every row
affected by the trigger event, or just once per SQL
statement. If neither is specified, for each statement is the
default.
✔ Funcname: A user-supplied function that is declared as
taking no arguments and returning type trigger, which is
executed when the trigger fires.
PostgreSQL Statements 37
39. TRIGGERS (7/11)
● CREATE TRIGGER
Example
CREATE FUNCTION emp_stamp() RETURNS trigger AS
$emp_stamp$
BEGIN
IF NEW.empname IS NULL THEN
RAISE EXCEPTION 'Nhap ten nhan vien';
END IF;
IF NEW.salary IS NULL THEN
RAISE EXCEPTION 'Nhap tien luong', NEW.empname;
END IF;
PostgreSQL Statements 39
40. TRIGGERS (8/11)
● CREATE TRIGGER
Example
NEW.last_date := current_timestamp;
NEW.last_user := current_user;
RETURN NEW;
END;
$emp_stamp$ LANGUAGE plpgsql;
CREATE TRIGGER emp_stamp BEFORE INSERT OR
UPDATE ON emp
FOR EACH ROW EXECUTE PROCEDURE emp_stamp();
PostgreSQL Statements 40
41. TRIGGERS (9/11)
● Several special variables
NEW: Data type RECORD; variable holding the new
database row for INSERT/UPDATE operations in
row-level triggers. This variable is NULL in
statement-level triggers.
OLD: Data type RECORD; variable holding the old
database row for UPDATE/DELETE operations in
row-level triggers. This variable is NULL in
statement-level triggers.
PostgreSQL Statements 41
42. TRIGGERS (10/11)
● Several special variables
TG_NAME: Data type name; variable that contains
the name of the trigger actually fired.
TG_WHEN: Data type text; a string of either
BEFORE or AFTER depending on the trigger's
definition.
TG_LEVEL: Data type text; a string of either ROW or
STATEMENT depending on the trigger's definition.
TG_OP: Data type text; a string of INSERT,
UPDATE, or DELETE telling for which operation the
trigger was fired.
PostgreSQL Statements 42
43. TRIGGERS (11/11)
● Several special variables
TG_RELID: Data type oid; the object ID of the table
that caused the trigger invocation.
TG_RELNAME: Data type name; the name of the
table that caused the trigger invocation.
TG_NARGS: Data type integer; the number of
arguments given to the trigger procedure in the
CREATE TRIGGER statement.
TG_ARGV[]: Data type array of text; the arguments
from the CREATE TRIGGER statement. The index
counts from 0. Invalid indices (less than 0 or greater
than or equal to tg_nargs) result in a null value.
PostgreSQL Statements 43
45. INDEXES (1/12)
● An index can be created in a table to find data
more quickly and efficiently.
● The users cannot see the indexes, they are just
used to speed up searches/queries.
● Note: Updating a table with indexes takes more
time than updating a table without (because the
indexes also need an update). So you should
only create indexes on columns (and tables)
that will be frequently searched against.
PostgreSQL Statements 45
46. INDEXES (2/12)
● CREATE INDEX Syntax
CREATE [ UNIQUE ] INDEX name ON table
[ USING method ] ( { column | ( expression ) }
[ opclass ] [, ...] )
[ TABLESPACE tablespace ]
[ WHERE predicate ]
PostgreSQL Statements 46
47. INDEXES (3/12)
● CREATE INDEX
Parameters
✔ UNIQUE: Causes the system to check for duplicate values
in the table when the index is created (if data already exist)
and each time data is added. Attempts to insert or update
data which would result in duplicate entries will generate an
error.
✔ Name: The name of the index to be created. No schema
name can be included here; the index is always created in
the same schema as its parent table.
✔ Table: The name (possibly schema-qualified) of the table to
be indexed.
PostgreSQL Statements 47
48. INDEXES (4/12)
● CREATE INDEX
Parameters
✔ Method: The name of the method to be used for the index.
Choices are btree, hash, rtree, and gist. The default
method is btree.
✔ Column: The name of a column of the table.
✔ Expression: An expression based on one or more columns
of the table. The expression usually must be written with
surrounding parentheses, as shown in the syntax.
However, the parentheses may be omitted if the expression
has the form of a function call.
PostgreSQL Statements 48
49. INDEXES (5/12)
● CREATE INDEX
Parameters
✔ Opclass: The name of an operator class. See below for
details.
✔ Tablespace: The tablespace in which to create the index.
✔ Predicate: The constraint expression for a partial index.
PostgreSQL Statements 49
50. INDEXES (6/12)
● CREATE INDEX
Example: The following command can be used to
create an index on the id column, as discussed:
✔ CREATE INDEX test1_id_index ON test1 (id);
PostgreSQL Statements 50
51. INDEXES (7/12)
● CREATE INDEX
Notice: An index can be defined on more than one
column of a table.
✔ CREATE INDEX test2_mm_idx ON test2 (major, minor);
PostgreSQL Statements 51
52. INDEXES (8/12)
● DROP INDEX Syntax
DROP INDEX drops an existing index from the
database system. To execute this command you
must be the owner of the index.
✔ DROP INDEX name [, ...] [ CASCADE | RESTRICT ]
Parameters
✔ Name: The name (optionally schema-qualified) of an index
to remove.
✔ CASCADE: Automatically drop objects that depend on the
index.
✔ RESTRICT: Refuse to drop the index if any objects depend
on it. This is the default.
PostgreSQL Statements 52
53. INDEXES (9/12)
● DROP INDEX
Example: This command will remove the index
title_idx:
✔ DROP INDEX title_idx;
PostgreSQL Statements 53
54. INDEXES (10/12)
● ALTER INDEX Syntax
ALTER INDEX name RENAME TO new_name
ALTER INDEX name SET TABLESPACE
tablespace_name
✔ ALTER INDEX changes the definition of an existing index.
✔ RENAME: The RENAME form changes the name of the
index. There is no effect on the stored data.
✔ SET TABLESPACE: This form changes the index's
tablespace to the specified tablespace and moves the data
file(s) associated with the index to the new tablespace
PostgreSQL Statements 54
55. INDEXES (11/12)
● ALTER INDEX
Parameters
✔ Name: The name (possibly schema-qualified) of an existing
index to alter.
✔ new_name: New name for the index.
✔ tablespace_name: The tablespace to which the index will
be moved.
PostgreSQL Statements 55
56. INDEXES (12/12)
● ALTER INDEX
Examples:
✔ To rename an existing index:
ALTER INDEX distributors RENAME TO suppliers;
✔ To move an index to a different tablespace:
ALTER INDEX distributors SET TABLESPACE fasttablespace;
PostgreSQL Statements 56