59
www.elarion.com PostgreSQL Statements LARION_TDT@Internship_03 Never stop improving quality

Postgre sql statements 03

Embed Size (px)

Citation preview

Page 1: Postgre sql statements 03

www.elarion.com

PostgreSQL Statements

LARION_TDT@Internship_03

Never stop improving quality

Page 2: Postgre sql statements 03

MEMBERS● Huy Phan-Dang● Phuc Nguyen-Dang-Hong● Vu Nguyen-Dinh-Hoang● Le Huynh● Duy Nguyen-Van

Page 3: Postgre sql statements 03

3PostgreSQL Statements

CONTENTS● Functions● Views● Triggers● Indexes

Page 4: Postgre sql statements 03

4PostgreSQL Statements

CONTENTS● Functions● Views● Triggers● Indexes

Page 5: Postgre sql statements 03

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.

Page 6: Postgre sql statements 03

6PostgreSQL Statements

FUNCTIONS (2/18)● CREATE FUNCTION - define a new function.● DROP FUNCTION - remove a function.● ALTER FUNCTION - change the definition of a

function.

Page 7: Postgre sql statements 03

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.

Page 8: Postgre sql statements 03

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).

Page 9: Postgre sql statements 03

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.

Page 10: Postgre sql statements 03

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).

Page 11: Postgre sql statements 03

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.

Page 12: Postgre sql statements 03

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.

Page 13: Postgre sql statements 03

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);

Page 14: Postgre sql statements 03

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

Page 15: Postgre sql statements 03

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);

Page 16: Postgre sql statements 03

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.

Page 17: Postgre sql statements 03

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.

Page 18: Postgre sql statements 03

18PostgreSQL Statements

FUNCTIONS (14/18)● DROP FUNCTION

Example✔ This command removes the square root function

DROP FUNCTION sqrt(integer);

Page 19: Postgre sql statements 03

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

Page 20: Postgre sql statements 03

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.

Page 21: Postgre sql statements 03

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.

Page 22: Postgre sql statements 03

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;

Page 23: Postgre sql statements 03

23PostgreSQL Statements

CONTENTS● Functions● Views● Triggers● Indexes

Page 24: Postgre sql statements 03

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.

Page 25: Postgre sql statements 03

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).

Page 26: Postgre sql statements 03

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.

Page 27: Postgre sql statements 03

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.

Page 28: Postgre sql statements 03

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

Page 29: Postgre sql statements 03

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.

Page 30: Postgre sql statements 03

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.

Page 31: Postgre sql statements 03

31PostgreSQL Statements

VIEWS (8/8)● DROP VIEW

Examples: This command will remove the view called kinds:✔ DROP VIEW kinds;

Page 32: Postgre sql statements 03

32PostgreSQL Statements

CONTENTS● Functions● Views● Triggers● Indexes

Page 33: Postgre sql statements 03

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.

Page 34: Postgre sql statements 03

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.

Page 35: Postgre sql statements 03

35PostgreSQL Statements

TRIGGERS (3/11)● CREATE TRIGGER

CREATE TRIGGER name { BEFORE | AFTER } { event [ OR ... ] }ON table [ FOR [ EACH ] { ROW | STATEMENT } ]EXECUTE PROCEDURE funcname ( arguments )

Page 36: Postgre sql statements 03

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.

Page 37: Postgre sql statements 03

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.

Page 38: Postgre sql statements 03

38PostgreSQL Statements

TRIGGERS (6/11)● CREATE TRIGGER

ExampleCREATE TABLE emp ( empname text, salary integer, last_date timestamp, last_user text);

Page 39: Postgre sql statements 03

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;

Page 40: Postgre sql statements 03

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();

Page 41: Postgre sql statements 03

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.

Page 42: Postgre sql statements 03

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.

Page 43: Postgre sql statements 03

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.

Page 44: Postgre sql statements 03

44PostgreSQL Statements

CONTENTS● Functions● Views● Triggers● Indexes

Page 45: Postgre sql statements 03

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.

Page 46: Postgre sql statements 03

46PostgreSQL Statements

INDEXES (2/12)● CREATE INDEX Syntax

CREATE [ UNIQUE ] INDEX name ON table [ USING method ] ( { column | ( expression ) } [ opclass ] [, ...] ) [ TABLESPACE tablespace ] [ WHERE predicate ]

Page 47: Postgre sql statements 03

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.

Page 48: Postgre sql statements 03

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.

Page 49: Postgre sql statements 03

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.

Page 50: Postgre sql statements 03

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);

Page 51: Postgre sql statements 03

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);

Page 52: Postgre sql statements 03

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.

Page 53: Postgre sql statements 03

53PostgreSQL Statements

INDEXES (9/12)● DROP INDEX

Example: This command will remove the index title_idx:✔ DROP INDEX title_idx;

Page 54: Postgre sql statements 03

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

Page 55: Postgre sql statements 03

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.

Page 56: Postgre sql statements 03

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;

Page 57: Postgre sql statements 03

57PostgreSQL Statements

Reference● PostgreSQL 9.1.0 Documentation● pgadmin.org

Page 58: Postgre sql statements 03

58PostgreSQL Statements

Questions & Answers

?

Page 59: Postgre sql statements 03

59PostgreSQL Statements

Thanks for your attention!