Sunday, July 17, 2011

Iterative Control in PL/pgSQL

LOOP Statements
  • Loops repeat a statement or sequence of statements multiple times.
  • There are three loop types:
    • Basic loop
    • FOR loop
    • WHILE loop
Basic Loops
  • Syntax :
          LOOP
          statement1;
          . . .
          EXIT [WHEN condition];
          END LOOP;
  • Example :
         create or replace function f2() returns void as
         $$
         DECLARE
         ctr numeric:=0;
         BEGIN
               LOOP
                     raise notice '%',ctr;
                     ctr:=ctr+1;
                     EXIT WHEN ctr > 3;
               END LOOP;
         END;
$$ language plpgsql;

WHILE Loops
  • Syntax :
          WHILE condition LOOP
          statement1;
          statement2;
          . . .
          END LOOP;
  • Use the WHILE loop to repeat statements 
  • while a condition is TRUE.
FOR Loops
  • Use a FOR loop to shortcut the test for the numeric of iterations.
  • Do not declare the counter; it is declared implicitly.
  • 'lower_bound .. upper_bound' is required syntax.
          FOR counter IN [REVERSE]
          lower_bound..upper_bound LOOP
          statement1;
          statement2;
          . . .
          END LOOP;
  • Example :
          create or replace function f3() returns void as
          $$
          BEGIN
          FOR ctr IN 1..3 LOOP
          raise notice '%',ctr;
          END LOOP;
          END;
          $$ language plpgsql;

Loop through Query Results



FOR record_or_row IN query LOOP
statements
END LOOP [ label ];
create or replace function f4() returns void as
$$
DECLARE
rec emp%ROWTYPE;
BEGIN
FOR rec IN select * from emp LOOP
raise notice '%',rec.ename;
END LOOP;
END;
$$ language plpgsql;

Saturday, July 16, 2011

Controlling Flow of Execution in plsql

Controlling Flow of Execution


IF Statements


Syntax:

IF condition THEN
statements;
[ELSIF condition THEN
statements;]
[ELSE
statements;]
END IF;


Simple IF Statement

DECLARE
myage numeric:=31;
BEGIN
IF myage < 11
THEN
raise notice ' I am a child ';
END IF;
END;


IF THEN ELSE Statement

DECLARE
myage numeric:=31;
BEGIN
IF myage < 11
THEN
raise notice ' I am a child ';
ELSE
raise notice ' I am not a child ';
END IF;
END;


CASE Expressions: Example

DECLARE
grade varchar := UPPER('a');
appraisal varchar(20);
BEGIN
appraisal :=
CASE grade
WHEN 'A' THEN 'Excellent'
WHEN 'B' THEN 'Very Good'
WHEN 'C' THEN 'Good'
ELSE 'No such grade'
END;
END;



Friday, July 15, 2011

The %TYPE Attribute in PL/pgSQL

The %TYPE attribute
  • Is used to declare a variable according to : 
    • A database column definition
    • Another declared variable
  • Is prefixed with :
    • The database table and column
    • The name of the declared variable


Declaring Variables with the %TYPE Attribute


Syntax :
identifier table.column_name%TYPE;


Examples :
emp_name emp.ename%TYPE;
balance NUMERIC;
min_balance balance%TYPE := 1000;




Wednesday, July 13, 2011

Use of Variables in PL/pgSQL

Variables can be used for :
  • Temporary storage of data
  • Manipulation of stored values
  • Reusability

Handling Variables in PL/pgSQL

Variables are :
  • Declared and initialized in the declarative section
  • Used and assigned new values in the executable section
  • Passed as parameters to PL/pgSQL subprograms
  • Used to hold the output of a PL/pgSQL subprogram
         DECLARE
         emp_hiredate DATE;
         emp_deptno NUMERIC := 10;
         location VARCHAR(13) := 'Atlanta';


Guidelines for Declaring PL/pgSQL Variables
  • Avoid using column names as identifiers.
  • Use the NOT NULL constraint when the variable must hold a value.

PL/pgSQL

PL/pgSQL Block Structure
  • DECLARE (Optional) 
    • Variables, 
    • cursors,
  • BEGIN (Mandatory) 
    • SQL statements 
    • PLPGSQL statements
  • EXCEPTION (Optional) 
    • Actions to perform when errors occur
  • END; (Mandatory)
  • All key words and identifiers can be written in mixed upper and lower case. Identifiers are implicitly converted to lowercase unless doublequoted.
  • There are two types of comments in PL/pgSQL.
    • -- starts a comment that extends to the end of the line.
    • /* multi-line comments */

Tuesday, July 12, 2011

Procedural Languages

Procedural Languages Overview
  • PostgreSQL allows user-defined functions to be written in a variety of procedural languages. 
  • The database server has no built-in knowledge about how to interpret the function's source text. 
  • Instead, the task is passed to a handler that knows the details of that particular language.
  • PostgreSQL currently supports several standard procedural languages :
    • PL/pgSQL
    • PL/Tcl
    • PL/Perl
    • PL/Python
    • PL/Java
    • PL/Ruby
    • Other languages can be defined by users
  • PL/pgSQL is a loadable procedural language for the PostgreSQL database system.
  • PL/pgSQL has several distinct features :
    • 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.

Monday, July 11, 2011

Indexes

An index:

  • Is a schema object
  • Can be used by the PostgreSQL server to speed up the retrieval of rows by using a pointer
  • Can reduce disk I/O by using a rapid path access method to locate data quickly
  • Is independent of the table that it indexes
  • Is used and maintained automatically by the PostgreSQL server
How Are Indexes Created?
  • Automatically : A unique index is created automatically when you define a PRIMARY KEY or UNIQUE constraint in a table definition.

  • Manually : Users can create non unique indexes on columns to speed up access to the rows.
Creating an Index
  • Create an index on one or more columns : 
         CREATE INDEX index ON table (column[, column]...);
  • Improve the speed of query access to the 
  • LAST_NAME column in the EMPLOYEES table :
         CREATE INDEX emp_last_name_idx ON employees(last_name);

Index Creation Guidelines :

Create an index when :
  • A column contains a wide range of values
  • A column contains a large number of null values
  • One or more columns are frequently used together in a WHERE clause or a join condition
  • The table is large and most queries are expected to retrieve less than 2% to 4% of the rows in the table
Do not create an index when :
  • The columns are not often used as a condition in the query
  • The table is small or most queries are expected to retrieve more than 2% to 4% of the rows in the table
  • The table is updated frequently
  • The indexed columns are referenced as part of an expression
Removing an Index
  • Remove an index from the data dictionary by using the DROP INDEX command :
          DROP INDEX index;
  • Remove the UPPER_LAST_NAME_IDX index 
  • from the data dictionary :
          DROP INDEX emp_last_name_idx;

Friday, July 8, 2011

Sequences

A sequence:
  • Can automatically generate unique numbers
  • Is a sharable object
  • Can be used to create a primary key value
  • Replaces application code
  • Speeds up the efficiency of accessing sequence values when cached in memory
CREATE SEQUENCE Statement: 
  • Define a sequence to generate sequential numbers automatically
  • Syntax:
        CREATE [ TEMPORARY | TEMP ] SEQUENCE name         
        [ INCREMENT [ BY ] increment ]         
        [ MINVALUE minvalue | NO MINVALUE ]         
        [ MAXVALUE maxvalue | NO MAXVALUE ]        
        [ START [ WITH ] start ]        
        [ CACHE cache ] [ [ NO ] CYCLE ]         
        [ OWNED BY { table.column | NONE } ]

Creating a Sequence
  • Create a sequence named DEPT_DEPTID_SEQ to be used for the primary key of the DEPARTMENTS table. 
  • Do not use the CYCLE option.
        CREATE SEQUENCE dept_deptid_seq 
                INCREMENT BY 10
                START WITH 120
                MAXVALUE 9999
                NO CYCLE;


NEXTVAL and CURRVAL Pseudocolumns
  • NEXTVAL returns the next available sequence value. It returns a unique value every time it is referenced, even for different users.
  • CURRVAL obtains the current sequence value.
  • NEXTVAL must be issued for that sequence before CURRVAL contains a value.
Using a Sequence
  • Insert a new department named “Support” in location Boston:
        INSERT INTO departments 
                       (department_id, department_name, location_id)
        VALUES (NEXTVAL(‘dept_deptid_seq’), 'Support', ‘Boston’);
  • View the current value for the DEPT_DEPTID_SEQ sequence:
        SELECT CURRVAL(‘dept_deptid_seq’);

Caching Sequence Values
  • Caching sequence values in memory gives faster access to those values.
  • Gaps in sequence values can occur when:
    • A rollback occurs
    • The system crashes
    • A sequence is used in another table
Modifying a Sequence
  • Change the increment value, maximum value, minimum value, cycle option, or cache option:
        ALTER SEQUENCE dept_deptid_seq
                    INCREMENT BY 20
                    MAXVALUE 999999
                   NO CYCLE;

Thursday, July 7, 2011

Creating a View

Creating a View
  •   You embed a subquery in the CREATE VIEW statement:
         CREATE [OR REPLACE] [TEMP|TEMPORARY  ] VIEW view
         [(column_name,..)] AS subquery

  • The subquery can contain complex SELECT syntax.
  •  Create the EMPVU80 view, which contains details of employees in department 80:
        CREATE VIEW empvu80  AS SELECT employee_id, last_name, salary
        FROM employees WHERE  department_id = 80;

  • Describe the structure of the view by using the psql \d command:
       \d empvu80

Retrieving Data from a View

SELECT * FROM   empvu80;


Creating a Complex View
  • Create a complex view that contains group functions to display values from two tables:
    CREATE OR REPLACE VIEW dept_sum_vu (name, minsal, maxsal, avgsal)
    AS SELECT   d.department_name, MIN(e.salary), MAX(e.salary),AVG(e.salary)
    FROM     employees e JOIN departments d
    ON       (e.department_id = d.department_id)
    GROUP BY d.department_name;


Removing a View
  • You can remove a view without losing data because a view is based on underlying tables in the database.
       Syntax :
       DROP VIEW view;

      Example :
      DROP VIEW empvu80;

Wednesday, July 6, 2011

Views

What Is a View?
  • A view is nothing but a window of an existing table by which one can view and can also change the values in tables. 
  • The main point aspect of view is views have no storage space. For this reason views are also called as virtual tables. 
  • Thus in other words a view is a database object that gives a logical representation of one or more database tables.
Advantages of Views
  • To restrict data access.
  • To make complex queries easy.
  • To provide data independence.
  • To present different views of the same data.
Simple Views and Complex Views

FeatureSimple ViewsComplex Views
Number of TablesOneOne or more
Contain FunctionsNoYes
Contain Group of DataNoYes

Followers