View
613
Download
7
Category
Preview:
Citation preview
www.elarion.com
PostgreSQL Statements
LARION_TDT@Internship_03
Never stop improving quality
MEMBERS● Huy Phan-Dang● Phuc Nguyen-Dang-Hong● Vu Nguyen-Dinh-Hoang● Le Huynh● Duy Nguyen-Van
3PostgreSQL Statements
CONTENTS● Functions● Views● Triggers● Indexes
4PostgreSQL Statements
CONTENTS● Functions● Views● Triggers● Indexes
5PostgreSQL Statements
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.
6PostgreSQL Statements
FUNCTIONS (2/18)● CREATE FUNCTION - define a new function.● DROP FUNCTION - remove a function.● ALTER FUNCTION - change the definition of a
function.
7PostgreSQL Statements
FUNCTIONS (3/18)● CREATE FUNCTION - define a new function.● Synopsis
CREATE FUNCTION name ( [ [ argmode ][ argname ] argtype [, …] ] )RETURNS returntypeAS 'definition'LANGUAGE 'langname'
● Create or Replace Function will either create a new function, or replace an existing definition.
8PostgreSQL Statements
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).
9PostgreSQL Statements
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.
10PostgreSQL Statements
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).
11PostgreSQL Statements
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.
12PostgreSQL Statements
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.
13PostgreSQL Statements
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);
14PostgreSQL Statements
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$ BEGININSERT INTO "user" (id,name,age) VALUES (id,username,age);END $BODY$LANGUAGE plpgsql
15PostgreSQL Statements
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);
16PostgreSQL Statements
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.
17PostgreSQL Statements
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.
18PostgreSQL Statements
FUNCTIONS (14/18)● DROP FUNCTION
Example✔ This command removes the square root function
DROP FUNCTION sqrt(integer);
19PostgreSQL Statements
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
20PostgreSQL Statements
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.
21PostgreSQL Statements
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.
22PostgreSQL Statements
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;
23PostgreSQL Statements
CONTENTS● Functions● Views● Triggers● Indexes
24PostgreSQL Statements
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.
25PostgreSQL Statements
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).
26PostgreSQL Statements
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.
27PostgreSQL Statements
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.
28PostgreSQL Statements
VIEWS (5/8)● CREATE VIEW
Examples: Create a view consisting of all comedy films:
CREATE VIEW comedies ASSELECT *FROM filmsWHERE kind = 'Comedy';
To use: SELECT * FROM comedies
29PostgreSQL Statements
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.
30PostgreSQL Statements
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.
31PostgreSQL Statements
VIEWS (8/8)● DROP VIEW
Examples: This command will remove the view called kinds:✔ DROP VIEW kinds;
32PostgreSQL Statements
CONTENTS● Functions● Views● Triggers● Indexes
33PostgreSQL Statements
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.
34PostgreSQL Statements
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.
35PostgreSQL Statements
TRIGGERS (3/11)● CREATE TRIGGER
CREATE TRIGGER name { BEFORE | AFTER } { event [ OR ... ] }ON table [ FOR [ EACH ] { ROW | STATEMENT } ]EXECUTE PROCEDURE funcname ( arguments )
36PostgreSQL Statements
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.
37PostgreSQL Statements
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.
38PostgreSQL Statements
TRIGGERS (6/11)● CREATE TRIGGER
ExampleCREATE TABLE emp ( empname text, salary integer, last_date timestamp, last_user text);
39PostgreSQL Statements
TRIGGERS (7/11)● CREATE TRIGGER
ExampleCREATE 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;
40PostgreSQL Statements
TRIGGERS (8/11)● CREATE TRIGGER
ExampleNEW.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();
41PostgreSQL Statements
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.
42PostgreSQL Statements
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.
43PostgreSQL Statements
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.
44PostgreSQL Statements
CONTENTS● Functions● Views● Triggers● Indexes
45PostgreSQL Statements
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.
46PostgreSQL Statements
INDEXES (2/12)● CREATE INDEX Syntax
CREATE [ UNIQUE ] INDEX name ON table [ USING method ] ( { column | ( expression ) } [ opclass ] [, ...] ) [ TABLESPACE tablespace ] [ WHERE predicate ]
47PostgreSQL Statements
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.
48PostgreSQL Statements
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.
49PostgreSQL Statements
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.
50PostgreSQL Statements
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);
51PostgreSQL Statements
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);
52PostgreSQL Statements
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.
53PostgreSQL Statements
INDEXES (9/12)● DROP INDEX
Example: This command will remove the index title_idx:✔ DROP INDEX title_idx;
54PostgreSQL Statements
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
55PostgreSQL Statements
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.
56PostgreSQL Statements
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;
57PostgreSQL Statements
Reference● PostgreSQL 9.1.0 Documentation● pgadmin.org
58PostgreSQL Statements
Questions & Answers
?
59PostgreSQL Statements
Thanks for your attention!
Recommended