Views, Sequence, and Stored Procedure used in PosgreSQL

Slides:



Advertisements
Similar presentations
AN INTRODUCTION TO PL/SQL Mehdi Azarmi 1. Introduction PL/SQL is Oracle's procedural language extension to SQL, the non-procedural relational database.
Advertisements

Instructor: Craig Duckett CASE, ORDER BY, GROUP BY, HAVING, Subqueries
Lecture-5 Though SQL is the natural language of the DBA, it suffers from various inherent disadvantages, when used as a conventional programming language.
Chapter 4B: More Advanced PL/SQL Programming
VBA Modules, Functions, Variables, and Constants
Introduction to Structured Query Language (SQL)
A Guide to Oracle9i1 Advanced SQL And PL/SQL Topics Chapter 9.
Introduction to Structured Query Language (SQL)
Bordoloi and Bock CURSORS. Bordoloi and Bock CURSOR MANIPULATION To process an SQL statement, ORACLE needs to create an area of memory known as the context.
PL / SQL P rocedural L anguage / S tructured Q uery L anguage Chapter 7 in Lab Reference.
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
Triggers A Quick Reference and Summary BIT 275. Triggers SQL code permits you to access only one table for an INSERT, UPDATE, or DELETE statement. The.
Overview · What is PL/SQL · Advantages of PL/SQL · Basic Structure of a PL/SQL Block · Procedure · Function · Anonymous Block · Types of Block · Declaring.
7 1 Chapter 7 Introduction to Structured Query Language (SQL) Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel.
CpSc 462/662: Database Management Systems (DBMS) (TEXNH Approach) Stored Procedure James Wang.
6 1 Lecture 8: Introduction to Structured Query Language (SQL) J. S. Chou, P.E., Ph.D.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
PL/SQL Block Structure DECLARE - Optional Variables, cursors, user-defined exceptions BEGIN - Mandatory SQL Statements PL/SQL Statements EXCEPTIONS - Optional.
Chapter 15 Introduction to PL/SQL. Chapter Objectives  Explain the benefits of using PL/SQL blocks versus several SQL statements  Identify the sections.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
SQL Fundamentals  SQL: Structured Query Language is a simple and powerful language used to create, access, and manipulate data and structure in the database.
Objectives Database triggers and syntax
PL/SQLPL/SQL Oracle10g Developer: PL/SQL Programming Chapter 9 Database Triggers.
PL/SQLPL/SQL Oracle10g Developer: PL/SQL Programming Chapter 9 Database Triggers.
Professor: Dr. Shu-Ching Chen TA: Hsin-Yu Ha Stored Procedure used in PosgreSQL.
Retrieving Data in PL/SQL. 2 home back first prev next last What Will I Learn? In this lesson, you will learn to: –Recognize the SQL statements that can.
Chapter 5 : Integrity And Security  Domain Constraints  Referential Integrity  Security  Triggers  Authorization  Authorization in SQL  Views 
implicit and an explicit cursor
Professor: Dr. Shu-Ching Chen TA: Hsin-Yu Ha Function, Trigger used in PosgreSQL.
Professor: Dr. Shu-Ching Chen TA: Hsin-Yu Ha Views, Sequence, and Stored Procedure used in PosgreSQL.
SQL Server 2012 Session: 1 Session: 12 Triggers Data Management Using Microsoft SQL Server.
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
IMS 4212: Constraints & Triggers 1 Dr. Lawrence West, Management Dept., University of Central Florida Stored Procedures in SQL Server.
Text TCS INTERNAL Oracle PL/SQL – Introduction. TCS INTERNAL PL SQL Introduction PLSQL means Procedural Language extension of SQL. PLSQL is a database.
Last Updated : 27 th April 2004 Center of Excellence Data Warehousing Group Teradata RDBMS Concepts.
Kingdom of Saudi Arabia Ministry of Higher Education Al-Imam Muhammad Ibn Saud Islamic University College of Computer and Information Sciences Overview.
SQL Triggers, Functions & Stored Procedures Programming Operations.
CS422 Principles of Database Systems Stored Procedures and Triggers Chengyu Sun California State University, Los Angeles.
Oracle 11g: SQL Chapter 5 Data Manipulation and Transaction Control.
Programming in postgreSQL with PL/pgSQL
More SQL: Complex Queries, Triggers, Views, and Schema Modification
ASP.NET Programming with C# and SQL Server First Edition
Trigger used in PosgreSQL
SQL Query Getting to the data ……..
A Guide to SQL, Seventh Edition
PL/pgSQL
Prof: Dr. Shu-Ching Chen TA: Hsin-Yu Ha
Instructor: Craig Duckett Lecture 09: Tuesday, April 25th, 2017
ATS Application Programming: Java Programming
Topics Introduction to Repetition Structures
Interacting with the Oracle Server
Oracle11g: PL/SQL Programming Chapter 4 Cursors and Exception Handling.
UNIT - V STORED PROCEDURE.
Stored Procedure used in PosgreSQL
PL/SQL Scripting in Oracle:
Prof: Dr. Shu-Ching Chen TA: Yimin Yang
Prof: Dr. Shu-Ching Chen TA: Hsin-Yu Ha
Stored Procedure used in PosgreSQL
Stored Procedure used in PosgreSQL
Exploring Microsoft® Access® 2016 Series Editor Mary Anne Poatsy
Chapter 2 Handling Data in PL/SQL Blocks Oracle9i Developer:
CS4222 Principles of Database System
SQL LANGUAGE and Relational Data Model TUTORIAL
Stored Procedure used in PosgreSQL
Prof: Dr. Shu-Ching Chen TA: Haiman Tian
Stored Procedure used in PosgreSQL
Oracle9i Developer: PL/SQL Programming Chapter 8 Database Triggers.
Chapter 8 Advanced SQL.
Prof. Arfaoui. COM390 Chapter 9
IST 318 Database Administration
Presentation transcript:

Views, Sequence, and Stored Procedure used in PosgreSQL Professor: Dr. Shu-Ching Chen TA:Sheng Guan

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.

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

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

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)

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

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)

Views in PostgreSQL (6) DROP VIEW view_name DROP VIEW CountryMAX DROP VIEW IF EXISTS CountryMAX

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.

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.

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 100000 START 1 CREATE SEQUENCE creates a new sequence number generator. CREATE TABLE products (product_id interger not null nextval(‘product_id_seq’), description text, );

Sequence in PostgreSQL (2) ALTER SEQUENCE seq_name ALTER SEQUENCE product_id START WITH 20 ALTER SEQUENCE product_id RESTART DROP SEQUENCE product_id

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

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.

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.

Declarations (1) Declaring PL/pgSQL variable

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.

Declarations (3) Declaring Function Parameters (1) directly give a name to the parameter in the command (2) name ALIAS FOR $n;

Declarations (4) Directly using argument variables

Declarations (5) Attributes %TYPE attribute

Declarations (6) Attributes %ROWTYPE attribute

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.

Basic Statements (1) Assignment Executing a Command with NO RESULT – PERFORM

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.

Basic Statements (3) Example

Basic Statements (4)

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

Control Structures(1) RETURN expression

Control Structures(2) IF statements IF … THEN IF … THEN … ELSE IF … THEN … ELSIF … THEN … ELSE

Control Structures(3) CASE statements CASE … WHEN … THEN … ELSE … END CASE CASE WHEN … THEN … ELSE … END CASE

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.

Control Structures(5) CONTINUE WHILE

Control Structures(6) FOR (Integer Variant)

Control Structures(7) FOR (Looping through query results)

Control Structures(8) Trapping Errors http://www.postgresql.org/docs/9.1/static/errcodes- 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.

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.

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.

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

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.

Errors and Messages RAISE Example

Reference PostgreSQL Manuals PostgreSQL 9.1 Practical PostgreSQL http://www.postgresql.org/docs/9.1/static/index.html Practical PostgreSQL http://www.faqs.org/docs/ppbook/c19610.htm 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. "

Stored Procedure in PgAdmin 3 2 1

Stored Procedure in PgAdmin