Download presentation
Presentation is loading. Please wait.
Published byAnna Barnett Modified over 6 years ago
1
Views, Sequence, and Stored Procedure used in PosgreSQL
Professor: Dr. Shu-Ching Chen TA:Sheng Guan
2
Types of SQL Statements
Data Definition Language (DDL) Statements CREATE, ALTER, DROP Data Control Language Statements GRANT, REVOKE Data Manipulation Language (DML) Statements INSERT, DELETE, UPDATE Transaction Control Statements Session Control Statements Data definition language (DDL) statements let you to perform these tasks: Create, alter, and drop schema objects DCL You use DCL statements to grant and revoke access to database objects and change ownership of those objects from one user or database to another. The results of DCL statement processing also are recorded in the Data Dictionary. Data manipulation language (DML) statements access and manipulate data in existing schema objects. These statements do not implicitly commit the current transaction. The data manipulation language statements are: Transaction control statements manage changes made by DML statements. Session control statements dynamically manage the properties of a user session.
3
Views in PostgreSQL (1) What is view? Syntax
A virtual table based on the result-set of an SQL statement It contains rows and columns The fields in a view are fields from one or more tables Syntax CREATE (OR REPLACE) (RECURSIVE) VIEW view_name AS SQL Statements ALTER VIEW view_name AS SQL Statements DROP VIEW view_name UPDATE view_name
4
Views in PostgreSQL (2) SELECT Continent, Region, Code, Code2, Name
FROM country ORDER BY Continent, Region, Code CREATE VIEW CountryView AS SELECT Continent, Region, Code, Code2, Name FROM country ORDER BY Continent, Region, Code SELECT Continent, COUNT(*) FROM CountryView GROUP BY Continent SELECT a.Name, b.Language FROM CountryView as a, countrylanguage as b WHERE a.Code = b.CountryCode
5
Views in PostgreSQL (3) CREATE [OR REPLACE] VIEW view_name
AS SQL Statement CREATE VIEW CountryMAXGNP AS SELECT Name, GNP FROM country WHERE (Region, GNP) IN ( SELECT Region, MAX(GNP) GROUP BY Region) CREATE OR REPLACE VIEW CountryMAXGNP AS SELECT Code, Name, GNP FROM country WHERE (Region, GNP) IN ( SELECT Region, MAX(GNP) GROUP BY Region) CREATE VIEW CountryMAXGNP AS SELECT Code, Name, GNP FROM country WHERE (Region, GNP) IN ( SELECT Region, MAX(GNP) GROUP BY Region)
6
Views in PostgreSQL (4) SELECT co.Name, ci.Name, co.Population, ci.Population, ROUND(ci.Population / co.Population, 2) Scale FROM country co, city ci WHERE co.Code = ci.CountryCode CREATE VIEW ScaleView AS SELECT co.Name, ci.Name, co.Population, ci.Population , ROUND(ci.Population / co.Population, 2) Scale FROM country co, city ci WHERE co.Code = ci.CountryCode CREATE VIEW ScaleView (CountryName, CityName, CountryPop, CityPop, Scale) AS SELECT co.Name, ci.Name, co.Population, ci.Population, ROUND(ci.Population / co.Population, 2) Scale FROM country co, city ci WHERE co.Code = ci.CountryCode CREATE VIEW ScaleView AS SELECT co.Name CountryName, ci.Name CityName, co.Population CountryPop, ci.Population CityPop, ROUND(ci.Population / co.Population, 2) Scale FROM country co, city ci WHERE co.Code = ci.CountryCode
7
Views in PostgreSQL (5) ALTER VIEW view_name AS SQL Statement
ALTER VIEW CountryMAXGNP AS SELECT Continent, Code, Name, GNP FROM country WHERE (Region, GNP) IN ( SELECT Region, MAX(GNP) GROUP BY Region) CREATE OR REPLACE VIEW CountryMAXGNP AS SELECT Continent, Code, Name, GNP FROM country WHERE (Region, GNP) IN ( SELECT Region, MAX(GNP) GROUP BY Region)
8
Views in PostgreSQL (6) DROP VIEW view_name DROP VIEW CountryMAX
DROP VIEW IF EXISTS CountryMAX
9
Views in PostgreSQL (7) CREATE VIEW comedies AS SELECT * FROM filems
WHERE kind= ‘Comedy’; CREATE VIEW universal_comedies AS SELECT * FROM comedies WHERE classification= ‘U’ WITH LOCAL CHECK OPTION; CREATE VIEW pg_comedies AS SELECT * FROM comedies WHERE classification= ‘PG’ WITH CASCADE CHECK OPTION; Any attempt to INSERT or UPDATE a row in the view will be rejected if the new row doesn't have classification = 'U', but the film kind will not be checked. This will create a view that checks both the kind and classification of new rows.
10
Views in PostgreSQL (8) Views can hide complexity
Views can be used as a security mechanism Many different perspectives of the same table you can use it for security. grant no permissions on the main table, create views that limits column or row access and grant permissions to users to see the view. you can use use it for convenience. join together some tables that you use together all the time in the view, can makes queries consistent and easier. Many different perspectives of the same table Can hide certain columns in a table. For example you may want to allow employees to see other employees to see the phone number column, but only certain employees to be able to access an employees salary column! Can provide huge time savings in writing queries by already having a group of frequently accessed tables joined together in a view. Views allow you to use functions and manipulate data in ways that meet your requirements. For example, you store a persons birth date, but you like to calculate this to determine their age.
11
Sequence in PostgreSQL (1)
CREATE SEQUENCE seq_name INCREMENT increment MINVALUE minvalue MAXVALUE maxvalue START startvalue CREATE SEQUENCE product_id_seq INCREMENT 1 MINVALUE 1 MAXVALUE START 1 CREATE SEQUENCE creates a new sequence number generator. CREATE TABLE products (product_id interger not null nextval(‘product_id_seq’), description text, );
12
Sequence in PostgreSQL (2)
ALTER SEQUENCE seq_name ALTER SEQUENCE product_id START WITH 20 ALTER SEQUENCE product_id RESTART DROP SEQUENCE product_id
13
What are stored procedures
A subroutine available to applications that access a relational database system. PL/pgSQL : A loadable procedural language. Creates functions and trigger procedures Adds control structures Performs complex computation Inherits all user-defined types, functions Can be defined to be trusted by the server Easy to use PL/pgSQL is a loadable procedural language for the PostgreSQL database system. The design goals of PL/pgSQL were to create a loadable procedural language that can be used to create functions and trigger procedures, adds control structures to the SQL language, can perform complex computations, inherits all user-defined types, functions, and operators, can be defined to be trusted by the server, is easy to use. A stored procedure is a subroutine available to applications that access a relational database system. Typical uses for stored procedures include data validation (integrated into the database) or access control mechanisms. Furthermore, stored procedures can consolidate and centralize logic that was originally implemented in applications. Extensive or complex processing that requires execution of several SQL statements is moved into stored procedures, and all applications call the procedures. One can use nested stored procedures, by executing one stored procedure from within another. Stored procedures are similar to user-defined functions (UDFs).
14
Why do we need stored procedure
Reduce roundtrips across the network Can make security easier to manage Are precompiled One Query Wait, receive, process/compute Database Server Internet Reduce roundtrips across the network - Stored procedures take zero or more input parameters, do something, and return a result, much like a function in any language. By “black boxing” that functionality on the database server, we avoid the need to move large datasets across the wire to the application server for processing. This can decrease network utilization and application latency. Can make security easier to manage - While views can help simplify the permissions needed for complex queries, stored procedures make it even easier. Instead of giving a user/application the correct rights to specific tables (or columns), a person only needs execution rights to the stored procedure. Are precompiled - Stored procedures are stored in a precomplied state on the server, meaning that the query optimizer doesn’t have to recalculate the most efficient execution path each time the query is run. This reduces server overhead and can speed things up a bit.
15
Structure of PL/pgSQL PL/pgSQL code is organized in blocks of code. This method of organization is known as block structured code. Code blocks are entered within a SQL CREATE FUNCTION call that creates the PL/pgSQL function in the PostgreSQL database. This CREATE FUNCTION command names the new function, states its argument types, and states the return type. The function's main code block then starts with a declaration section. All variables are declared and optionally initialized to a default value in the declaration section of a code block. A variable declaration specifies the variable's name and type. The declaration section is denoted by the DECLARE keyword. Each variable declaration is ended with a semicolon. After declaring variables, the main body of the code block is started with the BEGIN keyword. The code block's statements should appear after the BEGIN keyword. The END keyword designates the end of the code block. The main block of a PL/pgSQL function should return a value of its specified return type and end any sub-blocks (code blocks started within another code block) before its END keyword is reached.
16
Declarations (1) Declaring PL/pgSQL variable
17
Declarations (2) Declaring PL/pgSQL variable and assigning values
The NOT NULL keywords indicate that a variable cannot be set as NULL. The DEFAULT keyword allows you to provide a default value for a variable. Alternatively, you can use the := operator without specifying the DEFAULT keyword, to the same effect.
18
Declarations (3) Declaring Function Parameters
(1) directly give a name to the parameter in the command (2) name ALIAS FOR $n;
19
Declarations (4) Directly using argument variables
20
Declarations (5) Attributes %TYPE attribute
21
Declarations (6) Attributes %ROWTYPE attribute
22
Comment syntax Single-line comments Block comments
Single line comments begin with two dashes (- -) and have no end-character. The parser interprets all characters on the same line after the two dashes as part of the comment. The second type of comment is the multiline or block comment, which should be familiar to most anyone who has worked with programming languages before. Block comments begin with the forward slash and asterisk characters (/*) and end with the asterisk and forward slash characters (*/). Block comments can span multiple lines, and any text between the opening /* and closing */ is considered a comment. Example 11-7 shows the correct usage of a block comment.
23
Basic Statements (1) Assignment
Executing a Command with NO RESULT – PERFORM
24
Basic Statements (2) Executing a Command with a Single-row result
If the STRICT option is specified, the query must return exactly one row or a run-time error will be reported, either NO_DATA_FOUND (no rows) or TOO_MANY_ROWS (more than one row). You can use an exception block if you wish to catch the error, for example: where target can be a record variable, a row variable, or a comma-separated list of simple variables and record/row fields If STRICT is not specified in the INTO clause, then target will be set to the first row returned by the query, or to nulls if the query returned no rows. (Note that "the first row" is not well-defined unless you've used ORDER BY.) Any result rows after the first row are discarded.
25
Basic Statements (3) Example
26
Basic Statements (4)
27
Basic Statements (5) FOUND – Boolean variable
Use the special FOUND Boolean variable directly after a SELECT INTO statement to check whether or not the statement successfully inserted a value into the specified variable
28
Control Structures(1) RETURN expression
29
Control Structures(2) IF statements IF … THEN IF … THEN … ELSE
IF … THEN … ELSIF … THEN … ELSE
30
Control Structures(3) CASE statements
CASE … WHEN … THEN … ELSE … END CASE CASE WHEN … THEN … ELSE … END CASE
31
Control Structures(4) LOOP EXIT
LOOP defines an unconditional loop that is repeated indefinitely until terminated by an EXIT or RETURN statement. The optional label can be used by EXIT and CONTINUE statements within nested loops to specify which loop those statements refer to. If no label is given, the innermost loop is terminated and the statement following END LOOP is executed next. If label is given, it must be the label of the current or some outer level of nested loop or block. Then the named loop or block is terminated and control continues with the statement after the loop's/block's corresponding END. If WHEN is specified, the loop exit occurs only if boolean-expression is true. Otherwise, control passes to the statement after EXIT. EXIT can be used with all types of loops; it is not limited to use with unconditional loops. When used with a BEGIN block, EXIT passes control to the next statement after the end of the block. Note that a label must be used for this purpose; an unlabelled EXIT is never considered to match a BEGIN block.
32
Control Structures(5) CONTINUE WHILE
33
Control Structures(6) FOR (Integer Variant)
34
Control Structures(7) FOR (Looping through query results)
35
Control Structures(8) Trapping Errors
appendix.html#ERRCODES-TABLE If no error occurs, this form of block simply executes all the statements, and then control passes to the next statement afterEND. But if an error occurs within the statements, further processing of the statements is abandoned, and control passes to the EXCEPTION list. The list is searched for the first condition matching the error that occurred. If a match is found, the corresponding handler_statements are executed, and then control passes to the next statement after END. If no match is found, the error propagates out as though the EXCEPTION clause were not there at all: the error can be caught by an enclosing block with EXCEPTION, or if there is none it aborts processing of the function.
36
Cursors (1) Declaring Cursor Variables OPEN FOR query
This provides an efficient way to return large row sets from functions. Rather than executing a whole query at once, it is possible to set up a cursor that encapsulates the query, and then read the query result a few rows at a time create a cursor variable is just to declare it as a variable of type refcursor All three of these variables have the data type refcursor, but the first can be used with any query, while the second has a fully specified query already bound to it, and the last has a parameterized query bound to it. Before a cursor can be used to retrieve rows, it must be opened. (This is the equivalent action to the SQL command DECLARE CURSOR.) PL/pgSQL has three forms of the OPENstatement, two of which use unbound cursor variables while the third uses a bound cursor variable.
37
Cursors (2) Using Cursors FETCH MOVE NEXT PRIOR FIRST LAST
ABSOLUTE count RELATIVE count FORWARD BACKWORD Using Cursors FETCH MOVE NEXT Fetch the next row. This is the default if direction is omitted. PRIOR Fetch the prior row. FIRST Fetch the first row of the query (same as ABSOLUTE 1). LAST Fetch the last row of the query (same as ABSOLUTE -1). ABSOLUTE count Fetch the count'th row of the query, or the abs(count)'th row from the end if count is negative. Position before first row or after last row if count is out of range; in particular, ABSOLUTE 0 positions before the first row. RELATIVE count Fetch the count'th succeeding row, or the abs(count)'th prior row if count is negative. RELATIVE 0 re-fetches the current row, if any.
38
Cursors (3) Using Cursors CLOSE Returning Cursor
CLOSE closes the portal underlying an open cursor. This can be used to release resources earlier than end of transaction, or to free up the cursor variable to be opened again
39
Cursors (4) Looping Through a Cursor’s Result
The cursor variable must have been bound to some query when it was declared, and it cannot be open already. The FOR statement automatically opens the cursor, and it closes the cursor again when the loop exits. A list of actual argument value expressions must appear if and only if the cursor was declared to take arguments. These values will be substituted in the query, in just the same way as during an OPEN. The variable recordvar is automatically defined as type record and exists only inside the loop (any existing definition of the variable name is ignored within the loop). Each row returned by the cursor is successively assigned to this record variable and the loop body is executed.
40
Errors and Messages RAISE Example
41
Reference PostgreSQL Manuals PostgreSQL 9.1 Practical PostgreSQL
Practical PostgreSQL COST in stored procedures: A positive number giving the estimated execution cost for the function, in units of cpu_operator_cost. If the function returns a set, this is the cost per returned row. If the cost is not specified, 1 unit is assumed for C-language and internal functions, and 100 units for functions in all other languages. Larger values cause the planner to try to avoid evaluating the function more often than necessary. "
42
Stored Procedure in PgAdmin
3 2 1
43
Stored Procedure in PgAdmin
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.