SlideShare une entreprise Scribd logo
1  sur  93
Télécharger pour lire hors ligne
Processing Data Inside PostgreSQL

                                  BRUCE MOMJIAN,
                                   ENTERPRISEDB

                                   February, 2009




                                       Abstract
   There are indisputable advantages of doing data processing in the database
   rather than in each application. This presentation explores the ability to push
   data processing into the database using SQL, functions, triggers, and the
   object-relational features of POSTGRESQL.


Creative Commons Attribution License                       http://momjian.us/presentations
Pre-SQL Data Access


No one wants to return to this era:
    Complex cross-table access
 




    Single index
 




    No optimizer
 




    Simple WHERE processing
 




    No aggregation
 




Processing Data Inside PostgreSQL                         1
SQL Data Access


You probably take these for granted:

    Easy cross-table access, with optimizer assistance
 




    Complex WHERE processing
 




    Transaction Control
 




    Concurrency
 




    Portable language (SQL)
 




Processing Data Inside PostgreSQL                        2
Post-Ingres




Welcome to the
next generation
of data storage.


Processing Data Inside PostgreSQL                 3
Contents



1. SQL

2. Functions and Triggers

3. Customizing Database Features




Processing Data Inside PostgreSQL              4
1. SQL




Make full use of the
SQL tools available.




Processing Data Inside PostgreSQL            5
2. Functions and Triggers




Put your programs
in the database.



Processing Data Inside PostgreSQL                           6
3. Customizing Database Features




Change the
database features.



Processing Data Inside PostgreSQL                        7
1. SQL




Processing Data Inside PostgreSQL            8
Table Constraints
                         Table creation requires concentration.




Processing Data Inside PostgreSQL                                 9
Unique Test in an Application



    BEGIN;
    LOCK tab;
    SELECT ... WHERE col = key;
    if not found
        INSERT (or UPDATE)
    COMMIT;




Processing Data Inside PostgreSQL                          10
UNIQUE Constraint



    CREATE TABLE tab
    (
        col ... UNIQUE
    );
    CREATE TABLE customer (id INTEGER UNIQUE);




Processing Data Inside PostgreSQL                       11
Preventing NULLs



    if (col != NULL)
        INSERT/UPDATE;




Processing Data Inside PostgreSQL                      12
NOT NULL Constraint



    CREATE TABLE tab
    (
        col ... NOT NULL
    );
    CREATE TABLE customer (name TEXT NOT NULL);




Processing Data Inside PostgreSQL                         13
Primary Key Constraint



    UNIQUE
 




    NOT NULL
 




    CREATE TABLE customer (id INTEGER PRIMARY KEY);




Processing Data Inside PostgreSQL                            14
Ensuring Table Linkage
                                     Foreign —> Primary



    BEGIN;
    SELECT *
    FROM primary
    WHERE key = col
    FOR UPDATE;
    if found
        INSERT (or UPDATE) INTO foreign;
    COMMIT;




Processing Data Inside PostgreSQL                            15
Ensuring Table Linkage
                                     Primary —> Foreign



    BEGIN;
    SELECT *
    FROM foreign
    WHERE col = key
    FOR UPDATE;
    if found
        ?
    UPDATE/DELETE primary;
    COMMIT;




Processing Data Inside PostgreSQL                            16
Ensuring Table Linkage
                                           Example

    CREATE TABLE statename (
                       code CHAR(2) PRIMARY KEY,
                       name VARCHAR(30)
    );

    CREATE TABLE customer
    (
                                        customer_id   INTEGER,
                                        name          VARCHAR(30),
                                        telephone     VARCHAR(20),
                                        street        VARCHAR(40),
                                        city          VARCHAR(25),
                                        state         CHAR(2) REFERENCES statename,
                                        zipcode       CHAR(10),
                                        country       VARCHAR(20)
    );
Processing Data Inside PostgreSQL                                                     17
Ensuring Table Linkage
                                       Larger Example


    CREATE TABLE customer
    (
                              customer_id   INTEGER PRIMARY KEY,
                              name          VARCHAR(30),
                              telephone     VARCHAR(20),
                              street        VARCHAR(40),
                              city          VARCHAR(25),
                              state         CHAR(2),
                              zipcode       CHAR(10),
                              country       VARCHAR(20)
    );

    CREATE TABLE employee
    (
                              employee_id INTEGER PRIMARY KEY,
                              name        VARCHAR(30),
                              hire_date DATE
    );

    CREATE TABLE part (
Processing Data Inside PostgreSQL                                  18
part_id    INTEGER PRIMARY KEY,
                          name       VARCHAR(30),
                          cost       NUMERIC(8,2),
                          weight     FLOAT
    );

    CREATE TABLE salesorder (
                                order_id      INTEGER,
                                customer_id   INTEGER REFERENCES customer,
                                employee_id   INTEGER REFERENCES employee,
                                part_id       INTEGER REFERENCES part,
                                order_date    DATE,
                                ship_date     DATE,
                                payment       NUMERIC(8,2)
    );




Processing Data Inside PostgreSQL                                            19
Ensuring Table Linkage
                              Prevent Change to Primary



    BEGIN;
    SELECT ...
    FROM foreign
    WHERE col = key
    FOR UPDATE;
    IF found
        ABORT;
    UPDATE/DELETE primary;
    COMMIT;




Processing Data Inside PostgreSQL                         20
Ensuring Table Linkage
                         REFERENCES Constraint
                      NO ACTION/RESTRICT (default)



    CREATE TABLE foreign
    (
        col ... REFERENCES primary (col)
                ON UPDATE NO ACTION -- not required
                ON DELETE NO ACTION -- not required
    );




Processing Data Inside PostgreSQL                     21
Ensuring Table Linkage
                             Cascade Change to Primary



    BEGIN;
    SELECT ...
    FROM foreign
    WHERE col = key
    FOR UPDATE;
    IF found
        UPDATE/DELETE foreign;
    UPDATE/DELETE primary;
    COMMIT;




Processing Data Inside PostgreSQL                        22
Ensuring Table Linkage
                               REFERENCES Constraint
                                      CASCADE



    CREATE TABLE foreign
    (
        col ... REFERENCES primary (col)
                ON UPDATE CASCADE
                ON DELETE CASCADE
    );




Processing Data Inside PostgreSQL                        23
Ensuring Table Linkage
             Set Foreign to NULL on Change to Primary



    BEGIN;
    SELECT ...
    FROM foreign
    WHERE col = key
    FOR UPDATE;
    IF found
        UPDATE foreign SET col = NULL;
    UPDATE/DELETE primary;
    COMMIT;




Processing Data Inside PostgreSQL                       24
Ensuring Table Linkage
                               REFERENCES Constraint
                                      SET NULL



    CREATE TABLE foreign
    (
        col ... REFERENCES primary (col)
                ON UPDATE SET NULL
                ON DELETE SET NULL
    );




Processing Data Inside PostgreSQL                        25
Ensuring Table Linkage
        Set Foreign to DEFAULT on Change to Primary



    BEGIN;
    SELECT ...
    FROM foreign
    WHERE col = key
    FOR UPDATE;
    IF found
        UPDATE foreign SET col = DEFAULT;
    UPDATE/DELETE primary;
    COMMIT;




Processing Data Inside PostgreSQL                     26
Ensuring Table Linkage
                               REFERENCES Constraint
                                   SET DEFAULT



    CREATE TABLE foreign
    (
        col ... REFERENCES primary (col)
                ON UPDATE SET DEFAULT
                ON DELETE SET DEFAULT
    );

    CREATE TABLE order (cust_id INTEGER REFERENCES customer (id));




Processing Data Inside PostgreSQL                                    27
Controlling Data



    if col > 0 ...
       (col = 2 OR col = 7) ...
       length(col) < 10 ...
       INSERT/UPDATE tab;




Processing Data Inside PostgreSQL                      28
CHECK Constraint



    CREATE TABLE tab
    (
        col ... CHECK (col > 0 ...
    );

    CREATE TABLE customer (age INTEGER CHECK (age >= 0));




Processing Data Inside PostgreSQL                           29
Check Constraint Example



    CREATE TABLE friend2 (
                 firstname          VARCHAR(15),
                 lastname           VARCHAR(20),
                 city               VARCHAR(15),
                 state              CHAR(2)        CHECK
                                                   (length(trim(state)) = 2),
                 age                INTEGER        CHECK
                                                   (age >= 0),
                 gender             CHAR(1)        CHECK
                                                   (gender IN (’M’,’F’)),
                 last_met           DATE           CHECK
                                                   (last_met BETWEEN ’1950-01-01’
                                                    AND CURRENT_DATE),
                      CHECK (upper(trim(firstname)) != ’ED’ OR
                             upper(trim(lastname)) != ’RIVERS’)
    );

    INSERT INTO friend2
    VALUES (’Ed’, ’Rivers’, ’Wibbleville’, ’J’, -35, ’S’, ’1931-09-23’);

    ERROR: ExecAppend: rejected due to CHECK constraint friend2_last_met
Processing Data Inside PostgreSQL                                                   30
Default Column Values



    if col not specified
       col = DEFAULT;
    INSERT/UPDATE tab;




Processing Data Inside PostgreSQL                           31
DEFAULT Constraint



    CREATE TABLE tab
    (
        quantity ... DEFAULT 1
    );

    CREATE TABLE customer (created timestamp DEFAULT CURRENT_TIMESTAMP);




Processing Data Inside PostgreSQL                                          32
Auto-numbering Column



    CREATE TABLE counter (curr INTEGER);
    INSERT INTO counter VALUES (1);
    ...
    BEGIN;
    val = SELECT curr FROM counter FOR UPDATE;
    UPDATE counter SET curr = curr + 1;
    COMMIT;
    INSERT INTO tab VALUES (... val ...);




Processing Data Inside PostgreSQL                       33
SERIAL/Sequence



    CREATE TABLE tab
    (
        col SERIAL
    );

    CREATE TABLE tab
    (
        col INTEGER DEFAULT nextval(’tab_col_seq’)
    );

    CREATE TABLE customer (id SERIAL);

    CREATE SEQUENCE customer_id_seq;
    CREATE TABLE customer (id INTEGER DEFAULT nextval(’customer_id_seq’));


Processing Data Inside PostgreSQL                                            34
Constraint Macros
                                       DOMAIN



    CREATE DOMAIN phone AS
        CHAR(12) CHECK (VALUE ~ ’^[0-9]{3}-[0-9]{3}-[0-9]{4}$’);
    CREATE TABLE company ( ... phnum phone, ...);




Processing Data Inside PostgreSQL                                  35
Using
              SELECT’s
               Features


Processing Data Inside PostgreSQL   36
ANSI Outer Joins - LEFT OUTER



    SELECT *
    FROM tab1, tab2
    WHERE tab1.col = tab2.col
    UNION
    SELECT *
    FROM tab1
    WHERE col NOT IN
    (
        SELECT tab2.col
        FROM tab2
    );

    SELECT *
    FROM tab1 LEFT JOIN tab2 ON tab1.col = tab2.col;

Processing Data Inside PostgreSQL                      37
ANSI Outer Joins - RIGHT OUTER



    SELECT *
    FROM tab1, tab2
    WHERE tab1.col = tab2.col
    UNION
    SELECT *
    FROM tab2
    WHERE col NOT IN
    (
        SELECT tab1.col
        FROM tab1
    );

    SELECT *
    FROM tab1 RIGHT JOIN tab2 ON tab1.col = tab2.col;

Processing Data Inside PostgreSQL                       38
ANSI Outer Joins - FULL OUTER


    SELECT *
    FROM tab1, tab2
    WHERE tab1.col = tab2.col
    UNION
    SELECT *
    FROM tab1
    WHERE col NOT IN
    (
        SELECT tab2.col
        FROM tab2
    )
    UNION
    SELECT *
    FROM tab2
    WHERE col NOT IN
    (
        SELECT tab1.col
        FROM tab1
    );

    SELECT *
    FROM tab1 FULL JOIN tab2 ON tab1.col = tab2.col;
Processing Data Inside PostgreSQL                      39
ANSI Outer Join Example



    SELECT *
    FROM customer LEFT JOIN order ON customer.id = order.cust_id;




Processing Data Inside PostgreSQL                                   40
Aggregates
                                     SUM()



    total = 0
    FOREACH val IN set
        total = total + val;
    END FOREACH
    SELECT SUM(val) FROM tab;




Processing Data Inside PostgreSQL                41
Aggregates
                                     MAX()



    max = MIN_VAL;
    FOREACH val IN set
        if (val > max)
            max = val;
    END FOREACH

    SELECT MAX(val) FROM tab;

    SELECT MAX(cost) FROM part;




Processing Data Inside PostgreSQL                42
Aggregates
                                    GROUP BY SUM()

    qsort(set)

    save = ’’;
    total = 0;
    FOREACH val IN set
        if val != save and save != ’’
        {
            print save, total;
            save = val;
            total = 0;
        }
        total = total + amt;
    END FOREACH
    if save != ’’
        print save, total;

    SELECT val, SUM(amt) FROM tab GROUP BY val;
Processing Data Inside PostgreSQL                    43
Aggregates
                                    GROUP BY MAX()


    save = ’’;
    max = MIN_VAL;
    FOREACH val IN set
        if val != save and save != ’’
        {
            print save, max;
            save = val;
            max = MIN_VAL;
        }
        if (amt > max)
            max = amt;
    END FOREACH
    if save != ’’
        print save, max;

    SELECT val, MAX(amt) FROM tab GROUP BY val;
Processing Data Inside PostgreSQL                    44
Aggregates
                                    GROUP BY Examples



    SELECT part, COUNT(*)
    FROM order
    ORDER BY part;

    SELECT cust_id, SUM(due)
    FROM order
    GROUP BY cust_id
    ORDER BY 2 DESC;




Processing Data Inside PostgreSQL                       45
Merging SELECTs
                                        UNION



    SELECT     * INTO TEMP out FROM ...
    INSERT     INTO TEMP out SELECT ...
    INSERT     INTO TEMP out SELECT ...
    SELECT     DISTINCT ...

    SELECT *
    UNION
    SELECT *
    UNION
    SELECT *;




Processing Data Inside PostgreSQL                     46
Joining SELECTs
                                      INTERSECT



    SELECT * INTO TEMP out;
    DELETE FROM out WHERE out.* NOT IN (SELECT ...);
    DELETE FROM out WHERE out.* NOT IN (SELECT ...);

    SELECT *
    INTERSECT
    SELECT *
    INTERSECT
    SELECT *;




Processing Data Inside PostgreSQL                      47
Subtracting SELECTs
                                          EXCEPT



    SELECT * INTO TEMP out;
    DELETE FROM out WHERE out.* IN (SELECT ...);
    DELETE FROM out WHERE out.* IN (SELECT ...);

    SELECT *
    EXCEPT
    SELECT *
    EXCEPT
    SELECT *;




Processing Data Inside PostgreSQL                         48
Controlling Rows Returned
                                  LIMIT/OFFSET


    DECLARE limdemo CURSOR FOR SELECT ...
    FOR i = 1 to 5
        FETCH IN limdemo
    END FOR

    SELECT *
    LIMIT 5;

    DECLARE limdemo CURSOR FOR SELECT ...
    MOVE 20 IN limdemo
    FOR i = 1 to 5
        FETCH IN limdemo;
    END FOR

    SELECT *
    OFFSET 20 LIMIT 5;
Processing Data Inside PostgreSQL                        49
Controlling Rows Returned
                              LIMIT/OFFSET Example



    SELECT order_id, balance
    FROM order
    ORDER BY balance DESC
    LIMIT 10;




Processing Data Inside PostgreSQL                        50
Locking SELECT Rows
                                        FOR UPDATE



    BEGIN;
    LOCK tab;
    SELECT * FROM CUSTOMER WHERE id = 4452;
    UPDATE customer SET balance = 0 WHERE id = 4452;
    COMMIT;

    BEGIN;
    SELECT *
    FROM customer
    WHERE id = 4452
    FOR UPDATE;
    ...
    UPDATE customer
    SET balance = 0
Processing Data Inside PostgreSQL                         51
WHERE id = 4452;
    COMMIT;




Processing Data Inside PostgreSQL   52
Temporary Tables



    CREATE TABLE tab (...);
    ...
    DROP TABLE tab;

    CREATE TEMP TABLE tab (...);

    SELECT *
    INTO TEMPORARY hold
    FROM tab1, tab2, tab3
    WHERE ...




Processing Data Inside PostgreSQL                      53
Automatically Modify SELECT
                              VIEW - One Column



    SELECT col4
    FROM tab;

    CREATE VIEW view1 AS
    SELECT col4
    FROM tab;

    SELECT * FROM view1;




Processing Data Inside PostgreSQL                       54
Automatically Modify SELECT
                               VIEW - One Row



    SELECT *
    FROM tab
    WHERE col = ’ISDN’;

    CREATE VIEW view2 AS
    SELECT *
    FROM tab
    WHERE col = ’ISDN’;

    SELECT * FROM view2;




Processing Data Inside PostgreSQL                       55
Automatically Modify SELECT
                               VIEW - One Field



    SELECT col4
    FROM tab
    WHERE col = ’ISDN’;

    CREATE VIEW view3 AS
    SELECT col4
    FROM tab
    WHERE col = ’ISDN’;

    SELECT * FROM view3;




Processing Data Inside PostgreSQL                       56
Automatically Modify
                              INSERT/UPDATE/DELETE
                                      Rules



    INSERT INTO tab1 VALUES (...);
    INSERT INTO tab2 VALUES (...);

    CREATE RULE insert_tab1 AS ON INSERT TO tab1 DO
    INSERT INTO tab2 VALUES (...);

    INSERT INTO tab1 VALUES (...);




Processing Data Inside PostgreSQL                      57
Automatically Modify
                              INSERT/UPDATE/DELETE
                                   Rules Example

    CREATE TABLE service_request
    (
        customer_id INTEGER,
        description text,
       cre_user text DEFAULT CURRENT_USER,
       cre_timestamp timestamp DEFAULT CURRENT_TIMESTAMP
    );

    CREATE TABLE service_request_log
    (
        customer_id INTEGER,
        description text,
        mod_type char(1),
        mod_user text DEFAULT CURRENT_USER,
       mod_timestamp timestamp DEFAULT CURRENT_TIMESTAMP
    );
Processing Data Inside PostgreSQL                          58
Rules Example - Rule Definition



    CREATE RULE service_request_update AS -- UPDATE rule
    ON UPDATE TO service_request
    DO
        INSERT INTO service_request_log (customer_id, description, mod_type)
        VALUES (old.customer_id, old.description, ’U’);

    CREATE RULE service_request_delete AS -- DELETE rule
    ON DELETE TO service_request
    DO
        INSERT INTO service_request_log (customer_id, description, mod_type)
        VALUES (old.customer_id, old.description, ’D’);




Processing Data Inside PostgreSQL                                              59
Multi-User Consistency


     Atomic Changes
 




     Atomic Visibility
 




     Atomic Consistency
 




     Reliability
 




                                     User 1                               User 2                      Descrip
    BEGIN WORK                                                                              User 1 starts a t
    UPDATE   acct SET balance = balance - 100 WHERE acctno = 53224                          remove 100 from
    UPDATE   acct SET balance = balance + 100 WHERE acctno = 94913                          add 100 to an a
    SELECT   * FROM acct                                                                    sees both change
                                                                     SELECT   * FROM acct   sees no changes
    COMMIT WORK

                                                                     SELECT   * FROM acct   sees both change
Processing Data Inside PostgreSQL                                                                60
Notification
                                    LISTEN/NOTIFY



    signal()/kill()

    LISTEN myevent;
    NOTIFY myevent;




Processing Data Inside PostgreSQL                   61
Application Walk-through


                            Gborg, http://gborg.postgresql.org/




Processing Data Inside PostgreSQL                                 62
2. Functions and Triggers



                          Placing Code
                       Into the Database:
                      Server-side Functions




Processing Data Inside PostgreSQL                           63
Single-Parameter Built-In Functions/Operator



    SELECT factorial(10);
    factorial
    -----------
    3628800
    (1 row)

    SELECT 10!;
    ?column?
    ----------
    3628800
    (1 row)




Processing Data Inside PostgreSQL                        64
Two-Parameter Built-in Function/Operator



    SELECT date_mi(’2003-05-20’::date, ’2001-10-13’::date);
    date_mi
    ---------
    584
    (1 row)

    SELECT ’2003-05-20’::date - ’2001-10-13’::date;
    ?column?
    ----------
    584
    (1 row)

    psql df
    psql do

Processing Data Inside PostgreSQL                             65
Custom Server-Side Functions



    Create function
 




    Call function, manually or automatically
 




Processing Data Inside PostgreSQL                        66
Compute Sales Tax



    total = cost * 1.06;
    INSERT ... VALUES ( ... total ... );

    INSERT ... VALUES ( ... cost * 1.06, ... );

    CREATE FUNCTION total(float)
    RETURNS float
    AS ’SELECT $1 * 1.06;’
    LANGUAGE ’sql’;

    INSERT ... VALUES ( ... total(cost) ... )




Processing Data Inside PostgreSQL                       67
Convert Fahrenheit to Centigrade



    cent = (faren - 32.0) * 5.0 / 9.0
    INSERT ... VALUES ( ... cent ... )

    INSERT ... VALUES ( ... (faren - 32.0) * 5.0 / 9.0, ... )

    CREATE FUNCTION ftoc(float)
    RETURNS float
    AS ’SELECT ($1 - 32.0) * 5.0 / 9.0;’
    LANGUAGE ’sql’;

    INSERT ... VALUES ( ... ftoc(faren) ... )




Processing Data Inside PostgreSQL                               68
Compute Shipping Cost



    if cost < 2
        shipping = 3.00
    else if cost < 4
        shipping = 5.00
    else shipping = 6.00

    INSERT ... VALUES ( ... cost + shipping ... );




Processing Data Inside PostgreSQL                           69
Shipping Cost Function



    CREATE FUNCTION           shipping(numeric)
    RETURNS numeric
    AS ’SELECT CASE
            WHEN $1           < 2 THEN CAST(3.00 AS numeric(8,2))
            WHEN $1           >= 2 AND $1 < 4 THEN CAST(5.00 AS numeric(8,2))
            WHEN $1           >= 4 THEN CAST(6.00 AS numeric(8,2))
    END;’
    LANGUAGE ’sql’;

    INSERT ... VALUES ( ... cost + shipping(cost) ... );




Processing Data Inside PostgreSQL                                               70
String Processing — PL/pgSQL


    CREATE FUNCTION spread(text)
    RETURNS text
    AS $$
    DECLARE
        str text;
        ret text;
        i integer;
        len integer;
    BEGIN
        str := upper($1);
        ret := ’’; -- start with zero length
        i := 1;
        len := length(str);
        WHILE i <= len LOOP
            ret := ret || substr(str, i, 1) || ’ ’;
            i := i + 1;
        END LOOP;
        RETURN ret;
Processing Data Inside PostgreSQL                        71
END;
    $$
    LANGUAGE ’plpgsql’;

    SELECT spread(’Major Financial Report’);
                        spread
    ----------------------------------------------
     M A J O R F I N A N C I A L R E P O R T
    (1 row)




Processing Data Inside PostgreSQL                    72
State Name Lookup
                                    SQL Language Function



    SELECT name
    FROM statename
    WHERE code = ’AL’;

    CREATE FUNCTION getstatename(text)
    RETURNS text
    AS ’SELECT name
        FROM statename
        WHERE code = $1;’
    LANGUAGE ’sql’;

    SELECT getstatename(’AL’);


Processing Data Inside PostgreSQL                           73
State Name Lookup From String
                         PL/pgSQL Language Function


    CREATE FUNCTION getstatecode(text)
    RETURNS text
    AS $$
    DECLARE
       state_str statename.name%TYPE;
       statename_rec record;
       i integer;
       len integer;
       matches record;
       search_str text;
    BEGIN
        state_str := initcap($1); -- capitalization match column
        len := length(trim($1));
        i := 2;
        SELECT INTO statename_rec * -- first try for an exact match
        FROM statename
        WHERE name = state_str;
        IF FOUND
        THEN RETURN statename_rec.code;
        END IF;
Processing Data Inside PostgreSQL                                     74
WHILE i <= len LOOP -- test 2,4,6,... chars for match
             search_str = trim(substr(state_str, 1, i)) || ’%’;
             SELECT INTO matches COUNT(*)
             FROM statename
             WHERE name LIKE search_str;
             IF matches.count = 0 -- no matches, failure
             THEN RETURN NULL;
             END IF;
             IF matches.count = 1 -- exactly one match, return it
             THEN
                 SELECT INTO statename_rec *
                 FROM statename
                 WHERE name LIKE search_str;
                 IF FOUND
                 THEN RETURN statename_rec.code;
                 END IF;
             END IF;
             i := i + 2; -- >1 match, try 2 more chars
         END LOOP;
         RETURN ’’;
    END;
    $$
    LANGUAGE ’plpgsql’;


    SELECT getstatecode(’Alabama’);
    SELECT getstatecode(’ALAB’);
Processing Data Inside PostgreSQL                                   75
SELECT getstatecode(’Al’);
    SELECT getstatecode(’Ail’);




Processing Data Inside PostgreSQL   76
State Name Maintenance



    CREATE FUNCTION change_statename(char(2), char(30))
    RETURNS boolean
    AS $$
    DECLARE
        state_code ALIAS FOR $1;
        state_name ALIAS FOR $2;
        statename_rec RECORD;
    BEGIN
        IF length(state_code) = 0 -- no state code, failure
        THEN RETURN ’f’;
        ELSE
            IF length(state_name) != 0 -- is INSERT or UPDATE?
            THEN
                SELECT INTO statename_rec *
                FROM statename
                WHERE code = state_code;
                IF NOT FOUND -- is state not in table?
                THEN     INSERT INTO statename
                         VALUES (state_code, state_name);
                ELSE     UPDATE statename
                         SET name = state_name
Processing Data Inside PostgreSQL                                77
WHERE code = state_code;
                 END IF;
                 RETURN ’t’;
             ELSE -- is DELETE
                 SELECT INTO statename_rec *
                 FROM statename
                 WHERE code = state_code;
                 IF FOUND
                 THEN    DELETE FROM statename
                         WHERE code = state_code;
                         RETURN ’t’;
                 ELSE RETURN ’f’;
                 END IF;
             END IF;
         END IF;
    END;
    $$
    LANGUAGE ’plpgsql’;

    SELECT   change_statename(’AL’,’Alabama’);
    SELECT   change_statename(’AL’,’Bermuda’);
    SELECT   change_statename(’AL’,’’);
    SELECT   change_statename(’AL’,’’); -- row was already deleted




Processing Data Inside PostgreSQL                                    78
SELECT Inside FROM



    SELECT *
    FROM (SELECT * FROM tab) AS tab;

    SELECT *
    FROM ( SELECT 1,2,3,4,5 UNION
             SELECT 6,7,8,9,10 UNION
           SELECT 11,12,13,14,15) AS tab15;
    col| col| col| col| col
    ---+----+----+----+----
     1 | 2 | 3 | 4 | 5
     6 | 7 | 8 | 9 | 10
    11 | 12 | 13 | 14 | 15
    (3 rows)


Processing Data Inside PostgreSQL                        79
Function Returning
                                      Multiple Values



    CREATE TABLE int5(x1 INTEGER, x2 INTEGER, x3 INTEGER, x4 INTE-
    GER, x5 INTEGER);
    CREATE FUNCTION func5() RETURNS SETOF int5 AS
    ’SELECT 1,2,3,4,5;’
    LANGUAGE SQL;

    SELECT * FROM func5();
     x1 | x2 | x3 | x4 | x5
    ----+----+----+----+----
      1 | 2 | 3 | 4 | 5
    (1 row)



Processing Data Inside PostgreSQL                                    80
Function Returning
                                      a Table Result



    CREATE OR REPLACE FUNCTION func15() RETURNS SETOF int5 AS
    ’   SELECT 1,2,3,4,5 UNION
        SELECT 6,7,8,9,10 UNION
        SELECT 11,12,13,14,15;’
    LANGUAGE SQL;

    SELECT * FROM func15();
     x1 | x2 | x3 | x4 | x5
    ----+----+----+----+----
      1 | 2 | 3 | 4 | 5
      6 | 7 | 8 | 9 | 10
     11 | 12 | 13 | 14 | 15
    (3 rows)
Processing Data Inside PostgreSQL                               81
Automatic Function Calls
                                       Trigger



    BEFORE/AFTER ROW
 




    INSERT/UPDATE/DELETE
 




    OLD/NEW
 




Processing Data Inside PostgreSQL                         82
Trigger on Statename


    CREATE FUNCTION trigger_insert_update_statename()
    RETURNS trigger
    AS $$
    BEGIN
         IF new.code !~ ’^[A-Za-z][A-Za-z]$’
         THEN RAISE EXCEPTION ’State code must be two alphabetic characters.’;
         END IF;
         IF new.name !~ ’^[A-Za-z ]*$’
         THEN RAISE EXCEPTION ’State name must be only alphabetic characters.’;
         END IF;
         IF length(trim(new.name)) < 3
         THEN RAISE EXCEPTION ’State name must longer than two characters.’;
         END IF;
         new.code = upper(new.code); -- uppercase statename.code
         new.name = initcap(new.name); -- capitalize statename.name
         RETURN new;
    END;
    $$
Processing Data Inside PostgreSQL                                                 83
LANGUAGE ’plpgsql’;




Processing Data Inside PostgreSQL   84
Install Trigger
                                      On Statename



    CREATE TRIGGER trigger_statename
    BEFORE INSERT OR UPDATE
    ON statename
    FOR EACH ROW
    EXECUTE PROCEDURE trigger_insert_update_statename();

    INSERT     INTO    statename    VALUES   (’a’, ’alabama’);
    INSERT     INTO    statename    VALUES   (’al’, ’alabama2’);
    INSERT     INTO    statename    VALUES   (’al’, ’al’);
    INSERT     INTO    statename    VALUES   (’al’, ’alabama’);




Processing Data Inside PostgreSQL                                  85
Function Languages



    SQL
 




    PL/pgSQL
 




    PL/TCL
 




    PL/Python
 




    PL/Perl
 




    PL/sh
 




    C
 




Processing Data Inside PostgreSQL                        86
Function Examples




    /contrib/earthdistance
 




    /contrib/fuzzystringmatch
 




    /contrib/pgcrypto
 




Processing Data Inside PostgreSQL                       87
3. Customizing Database Features




     Adding New
   Data and Indexing
       Features



Processing Data Inside PostgreSQL                        88
Creation



    CREATE FUNCTIONS in C
 




    CREATE TYPE
 




    CREATE OPERATOR
 




    CREATE OPERATOR CLASS (index type)
 




Processing Data Inside PostgreSQL              89
Create New Data Type
                      With Operator and Index Support



    Write input/output functions
 




    Register input/output functions with CREATE FUNCTION
 




    Register type with CREATE TYPE
 




    Write comparison functions
 




    Register comparison functions with CREATE FUNCTION
 




    Register comparison functions with CREATE OPERATOR
 




    Register operator class for indexes with CREATE OPERATOR CLASS
 




Processing Data Inside PostgreSQL                               90
Create New Data Type
                                          Examples


    /contrib/chkpass
 




    /contrib/isn
 




    /contrib/cube
 




    /contrib/ltree
 




    /src/backend/utils/adt
 




Processing Data Inside PostgreSQL                          91
Conclusion




Processing Data Inside PostgreSQL                92

Contenu connexe

Tendances

Building node.js applications with Database Jones
Building node.js applications with Database JonesBuilding node.js applications with Database Jones
Building node.js applications with Database JonesJohn David Duncan
 
Oracle12c Pluggable Database Hands On - TROUG 2014
Oracle12c Pluggable Database Hands On - TROUG 2014Oracle12c Pluggable Database Hands On - TROUG 2014
Oracle12c Pluggable Database Hands On - TROUG 2014Özgür Umut Vurgun
 
Postgresql quick guide
Postgresql quick guidePostgresql quick guide
Postgresql quick guideAshoka Vanjare
 
Porting Applications From Oracle To PostgreSQL
Porting Applications From Oracle To PostgreSQLPorting Applications From Oracle To PostgreSQL
Porting Applications From Oracle To PostgreSQLPeter Eisentraut
 
How to export import a mysql database via ssh in aws lightsail wordpress rizw...
How to export import a mysql database via ssh in aws lightsail wordpress rizw...How to export import a mysql database via ssh in aws lightsail wordpress rizw...
How to export import a mysql database via ssh in aws lightsail wordpress rizw...AlexRobert25
 
Redis SoCraTes 2014
Redis SoCraTes 2014Redis SoCraTes 2014
Redis SoCraTes 2014steffenbauer
 
MySQL Slow Query log Monitoring using Beats & ELK
MySQL Slow Query log Monitoring using Beats & ELKMySQL Slow Query log Monitoring using Beats & ELK
MySQL Slow Query log Monitoring using Beats & ELKI Goo Lee
 
MySQL Audit using Percona audit plugin and ELK
MySQL Audit using Percona audit plugin and ELKMySQL Audit using Percona audit plugin and ELK
MySQL Audit using Percona audit plugin and ELKI Goo Lee
 
Entity Framework Core & Micro-Orms with Asp.Net Core
Entity Framework Core & Micro-Orms with Asp.Net CoreEntity Framework Core & Micro-Orms with Asp.Net Core
Entity Framework Core & Micro-Orms with Asp.Net CoreStephane Belkheraz
 
Why and How Powershell will rule the Command Line - Barcamp LA 4
Why and How Powershell will rule the Command Line - Barcamp LA 4Why and How Powershell will rule the Command Line - Barcamp LA 4
Why and How Powershell will rule the Command Line - Barcamp LA 4Ilya Haykinson
 
MySQL Audit using Percona audit plugin and ELK
MySQL Audit using Percona audit plugin and ELKMySQL Audit using Percona audit plugin and ELK
MySQL Audit using Percona audit plugin and ELKYoungHeon (Roy) Kim
 
My sql with querys
My sql with querysMy sql with querys
My sql with querysNIRMAL FELIX
 

Tendances (20)

Building node.js applications with Database Jones
Building node.js applications with Database JonesBuilding node.js applications with Database Jones
Building node.js applications with Database Jones
 
Sah
SahSah
Sah
 
MySQL
MySQLMySQL
MySQL
 
My sql tutorial-oscon-2012
My sql tutorial-oscon-2012My sql tutorial-oscon-2012
My sql tutorial-oscon-2012
 
Oracle12c Pluggable Database Hands On - TROUG 2014
Oracle12c Pluggable Database Hands On - TROUG 2014Oracle12c Pluggable Database Hands On - TROUG 2014
Oracle12c Pluggable Database Hands On - TROUG 2014
 
Firebird
FirebirdFirebird
Firebird
 
Postgresql quick guide
Postgresql quick guidePostgresql quick guide
Postgresql quick guide
 
Porting Applications From Oracle To PostgreSQL
Porting Applications From Oracle To PostgreSQLPorting Applications From Oracle To PostgreSQL
Porting Applications From Oracle To PostgreSQL
 
How to export import a mysql database via ssh in aws lightsail wordpress rizw...
How to export import a mysql database via ssh in aws lightsail wordpress rizw...How to export import a mysql database via ssh in aws lightsail wordpress rizw...
How to export import a mysql database via ssh in aws lightsail wordpress rizw...
 
Redis SoCraTes 2014
Redis SoCraTes 2014Redis SoCraTes 2014
Redis SoCraTes 2014
 
Mysql
MysqlMysql
Mysql
 
Mysql Ppt
Mysql PptMysql Ppt
Mysql Ppt
 
MySQL Slow Query log Monitoring using Beats & ELK
MySQL Slow Query log Monitoring using Beats & ELKMySQL Slow Query log Monitoring using Beats & ELK
MySQL Slow Query log Monitoring using Beats & ELK
 
MySQL Audit using Percona audit plugin and ELK
MySQL Audit using Percona audit plugin and ELKMySQL Audit using Percona audit plugin and ELK
MySQL Audit using Percona audit plugin and ELK
 
Entity Framework Core & Micro-Orms with Asp.Net Core
Entity Framework Core & Micro-Orms with Asp.Net CoreEntity Framework Core & Micro-Orms with Asp.Net Core
Entity Framework Core & Micro-Orms with Asp.Net Core
 
Why and How Powershell will rule the Command Line - Barcamp LA 4
Why and How Powershell will rule the Command Line - Barcamp LA 4Why and How Powershell will rule the Command Line - Barcamp LA 4
Why and How Powershell will rule the Command Line - Barcamp LA 4
 
MySQL Audit using Percona audit plugin and ELK
MySQL Audit using Percona audit plugin and ELKMySQL Audit using Percona audit plugin and ELK
MySQL Audit using Percona audit plugin and ELK
 
My sql with querys
My sql with querysMy sql with querys
My sql with querys
 
My sql.ppt
My sql.pptMy sql.ppt
My sql.ppt
 
Createclone
CreatecloneCreateclone
Createclone
 

En vedette

PostgreSQL Deep Internal
PostgreSQL Deep InternalPostgreSQL Deep Internal
PostgreSQL Deep InternalEXEM
 
PostgreSQL Performance Tuning
PostgreSQL Performance TuningPostgreSQL Performance Tuning
PostgreSQL Performance Tuningelliando dias
 
Mastering PostgreSQL Administration
Mastering PostgreSQL AdministrationMastering PostgreSQL Administration
Mastering PostgreSQL AdministrationEDB
 
Postgresql database administration volume 1
Postgresql database administration volume 1Postgresql database administration volume 1
Postgresql database administration volume 1Federico Campoli
 
Linux tuning to improve PostgreSQL performance
Linux tuning to improve PostgreSQL performanceLinux tuning to improve PostgreSQL performance
Linux tuning to improve PostgreSQL performancePostgreSQL-Consulting
 
A couple of things about PostgreSQL...
A couple of things  about PostgreSQL...A couple of things  about PostgreSQL...
A couple of things about PostgreSQL...Federico Campoli
 
Advanced User Privileges
Advanced User PrivilegesAdvanced User Privileges
Advanced User PrivilegesArena PLM
 
Constraints In Sql
Constraints In SqlConstraints In Sql
Constraints In SqlAnurag
 
Database index
Database indexDatabase index
Database indexRiteshkiit
 
User, roles and privileges
User, roles and privilegesUser, roles and privileges
User, roles and privilegesYogiji Creations
 
PostgreSQL Hangout Parameter Tuning
PostgreSQL Hangout Parameter TuningPostgreSQL Hangout Parameter Tuning
PostgreSQL Hangout Parameter TuningAshnikbiz
 
A brief introduction to PostgreSQL
A brief introduction to PostgreSQLA brief introduction to PostgreSQL
A brief introduction to PostgreSQLVu Hung Nguyen
 
Oracle Deep Internal 1 (ver.2)
Oracle Deep Internal 1 (ver.2)Oracle Deep Internal 1 (ver.2)
Oracle Deep Internal 1 (ver.2)EXEM
 

En vedette (20)

PostgreSQL Deep Internal
PostgreSQL Deep InternalPostgreSQL Deep Internal
PostgreSQL Deep Internal
 
PostgreSQL Performance Tuning
PostgreSQL Performance TuningPostgreSQL Performance Tuning
PostgreSQL Performance Tuning
 
Mastering PostgreSQL Administration
Mastering PostgreSQL AdministrationMastering PostgreSQL Administration
Mastering PostgreSQL Administration
 
Postgresql database administration volume 1
Postgresql database administration volume 1Postgresql database administration volume 1
Postgresql database administration volume 1
 
Get to know PostgreSQL!
Get to know PostgreSQL!Get to know PostgreSQL!
Get to know PostgreSQL!
 
PostgreSQL and RAM usage
PostgreSQL and RAM usagePostgreSQL and RAM usage
PostgreSQL and RAM usage
 
Linux tuning to improve PostgreSQL performance
Linux tuning to improve PostgreSQL performanceLinux tuning to improve PostgreSQL performance
Linux tuning to improve PostgreSQL performance
 
A couple of things about PostgreSQL...
A couple of things  about PostgreSQL...A couple of things  about PostgreSQL...
A couple of things about PostgreSQL...
 
5 Steps to PostgreSQL Performance
5 Steps to PostgreSQL Performance5 Steps to PostgreSQL Performance
5 Steps to PostgreSQL Performance
 
Les11 Including Constraints
Les11 Including ConstraintsLes11 Including Constraints
Les11 Including Constraints
 
Advanced User Privileges
Advanced User PrivilegesAdvanced User Privileges
Advanced User Privileges
 
Less07 Users
Less07 UsersLess07 Users
Less07 Users
 
Constraints In Sql
Constraints In SqlConstraints In Sql
Constraints In Sql
 
PostgreSQL: Advanced indexing
PostgreSQL: Advanced indexingPostgreSQL: Advanced indexing
PostgreSQL: Advanced indexing
 
Database index
Database indexDatabase index
Database index
 
User, roles and privileges
User, roles and privilegesUser, roles and privileges
User, roles and privileges
 
PostgreSQL Hangout Parameter Tuning
PostgreSQL Hangout Parameter TuningPostgreSQL Hangout Parameter Tuning
PostgreSQL Hangout Parameter Tuning
 
PostgreSQL
PostgreSQLPostgreSQL
PostgreSQL
 
A brief introduction to PostgreSQL
A brief introduction to PostgreSQLA brief introduction to PostgreSQL
A brief introduction to PostgreSQL
 
Oracle Deep Internal 1 (ver.2)
Oracle Deep Internal 1 (ver.2)Oracle Deep Internal 1 (ver.2)
Oracle Deep Internal 1 (ver.2)
 

Similaire à Processing Data Inside PostgreSQL Using SQL, Functions, Triggers

Oracle vs. SQL Server- War of the Indices
Oracle vs. SQL Server- War of the IndicesOracle vs. SQL Server- War of the Indices
Oracle vs. SQL Server- War of the IndicesKellyn Pot'Vin-Gorman
 
Intro to SQL by Google's Software Engineer
Intro to SQL by Google's Software EngineerIntro to SQL by Google's Software Engineer
Intro to SQL by Google's Software EngineerProduct School
 
Sql ch 12 - creating database
Sql ch 12 - creating databaseSql ch 12 - creating database
Sql ch 12 - creating databaseMukesh Tekwani
 
Session #4: Treating Databases as First-Class Citizens in Development
Session #4: Treating Databases as First-Class Citizens in DevelopmentSession #4: Treating Databases as First-Class Citizens in Development
Session #4: Treating Databases as First-Class Citizens in DevelopmentSteve Lange
 
PHX - Session #4 Treating Databases as First-Class Citizens in Development
PHX - Session #4 Treating Databases as First-Class Citizens in DevelopmentPHX - Session #4 Treating Databases as First-Class Citizens in Development
PHX - Session #4 Treating Databases as First-Class Citizens in DevelopmentSteve Lange
 
How to teach an elephant to rock'n'roll
How to teach an elephant to rock'n'rollHow to teach an elephant to rock'n'roll
How to teach an elephant to rock'n'rollPGConf APAC
 
Connecting and using PostgreSQL database with psycopg2 [Python 2.7]
Connecting and using PostgreSQL database with psycopg2 [Python 2.7]Connecting and using PostgreSQL database with psycopg2 [Python 2.7]
Connecting and using PostgreSQL database with psycopg2 [Python 2.7]Dinesh Neupane
 
Oracle trigger
Oracle triggerOracle trigger
Oracle triggernasrul28
 
Session 8 connect your universal application with database .. builders & deve...
Session 8 connect your universal application with database .. builders & deve...Session 8 connect your universal application with database .. builders & deve...
Session 8 connect your universal application with database .. builders & deve...Moatasim Magdy
 
Работа с реляционными базами данных в C++
Работа с реляционными базами данных в C++Работа с реляционными базами данных в C++
Работа с реляционными базами данных в C++corehard_by
 

Similaire à Processing Data Inside PostgreSQL Using SQL, Functions, Triggers (20)

database.pptx
database.pptxdatabase.pptx
database.pptx
 
Sql
SqlSql
Sql
 
greenDAO
greenDAOgreenDAO
greenDAO
 
Oracle vs. SQL Server- War of the Indices
Oracle vs. SQL Server- War of the IndicesOracle vs. SQL Server- War of the Indices
Oracle vs. SQL Server- War of the Indices
 
Intro to SQL by Google's Software Engineer
Intro to SQL by Google's Software EngineerIntro to SQL by Google's Software Engineer
Intro to SQL by Google's Software Engineer
 
Sql ch 12 - creating database
Sql ch 12 - creating databaseSql ch 12 - creating database
Sql ch 12 - creating database
 
Session #4: Treating Databases as First-Class Citizens in Development
Session #4: Treating Databases as First-Class Citizens in DevelopmentSession #4: Treating Databases as First-Class Citizens in Development
Session #4: Treating Databases as First-Class Citizens in Development
 
PHX - Session #4 Treating Databases as First-Class Citizens in Development
PHX - Session #4 Treating Databases as First-Class Citizens in DevelopmentPHX - Session #4 Treating Databases as First-Class Citizens in Development
PHX - Session #4 Treating Databases as First-Class Citizens in Development
 
How to teach an elephant to rock'n'roll
How to teach an elephant to rock'n'rollHow to teach an elephant to rock'n'roll
How to teach an elephant to rock'n'roll
 
Connecting and using PostgreSQL database with psycopg2 [Python 2.7]
Connecting and using PostgreSQL database with psycopg2 [Python 2.7]Connecting and using PostgreSQL database with psycopg2 [Python 2.7]
Connecting and using PostgreSQL database with psycopg2 [Python 2.7]
 
Rdbms day3
Rdbms day3Rdbms day3
Rdbms day3
 
Oracle trigger
Oracle triggerOracle trigger
Oracle trigger
 
MongoDB & PHP
MongoDB & PHPMongoDB & PHP
MongoDB & PHP
 
Session 8 connect your universal application with database .. builders & deve...
Session 8 connect your universal application with database .. builders & deve...Session 8 connect your universal application with database .. builders & deve...
Session 8 connect your universal application with database .. builders & deve...
 
Работа с реляционными базами данных в C++
Работа с реляционными базами данных в C++Работа с реляционными базами данных в C++
Работа с реляционными базами данных в C++
 
Mysql rab2-student
Mysql rab2-studentMysql rab2-student
Mysql rab2-student
 
Mysql rab2-student
Mysql rab2-studentMysql rab2-student
Mysql rab2-student
 
Db1 lecture4
Db1 lecture4Db1 lecture4
Db1 lecture4
 
SQL Overview
SQL OverviewSQL Overview
SQL Overview
 
chapter 8 SQL.ppt
chapter 8 SQL.pptchapter 8 SQL.ppt
chapter 8 SQL.ppt
 

Plus de EDB

Cloud Migration Paths: Kubernetes, IaaS, or DBaaS
Cloud Migration Paths: Kubernetes, IaaS, or DBaaSCloud Migration Paths: Kubernetes, IaaS, or DBaaS
Cloud Migration Paths: Kubernetes, IaaS, or DBaaSEDB
 
Die 10 besten PostgreSQL-Replikationsstrategien für Ihr Unternehmen
Die 10 besten PostgreSQL-Replikationsstrategien für Ihr UnternehmenDie 10 besten PostgreSQL-Replikationsstrategien für Ihr Unternehmen
Die 10 besten PostgreSQL-Replikationsstrategien für Ihr UnternehmenEDB
 
Migre sus bases de datos Oracle a la nube
Migre sus bases de datos Oracle a la nube Migre sus bases de datos Oracle a la nube
Migre sus bases de datos Oracle a la nube EDB
 
EFM Office Hours - APJ - July 29, 2021
EFM Office Hours - APJ - July 29, 2021EFM Office Hours - APJ - July 29, 2021
EFM Office Hours - APJ - July 29, 2021EDB
 
Benchmarking Cloud Native PostgreSQL
Benchmarking Cloud Native PostgreSQLBenchmarking Cloud Native PostgreSQL
Benchmarking Cloud Native PostgreSQLEDB
 
Las Variaciones de la Replicación de PostgreSQL
Las Variaciones de la Replicación de PostgreSQLLas Variaciones de la Replicación de PostgreSQL
Las Variaciones de la Replicación de PostgreSQLEDB
 
NoSQL and Spatial Database Capabilities using PostgreSQL
NoSQL and Spatial Database Capabilities using PostgreSQLNoSQL and Spatial Database Capabilities using PostgreSQL
NoSQL and Spatial Database Capabilities using PostgreSQLEDB
 
Is There Anything PgBouncer Can’t Do?
Is There Anything PgBouncer Can’t Do?Is There Anything PgBouncer Can’t Do?
Is There Anything PgBouncer Can’t Do?EDB
 
Data Analysis with TensorFlow in PostgreSQL
Data Analysis with TensorFlow in PostgreSQLData Analysis with TensorFlow in PostgreSQL
Data Analysis with TensorFlow in PostgreSQLEDB
 
Practical Partitioning in Production with Postgres
Practical Partitioning in Production with PostgresPractical Partitioning in Production with Postgres
Practical Partitioning in Production with PostgresEDB
 
A Deeper Dive into EXPLAIN
A Deeper Dive into EXPLAINA Deeper Dive into EXPLAIN
A Deeper Dive into EXPLAINEDB
 
IOT with PostgreSQL
IOT with PostgreSQLIOT with PostgreSQL
IOT with PostgreSQLEDB
 
A Journey from Oracle to PostgreSQL
A Journey from Oracle to PostgreSQLA Journey from Oracle to PostgreSQL
A Journey from Oracle to PostgreSQLEDB
 
Psql is awesome!
Psql is awesome!Psql is awesome!
Psql is awesome!EDB
 
EDB 13 - New Enhancements for Security and Usability - APJ
EDB 13 - New Enhancements for Security and Usability - APJEDB 13 - New Enhancements for Security and Usability - APJ
EDB 13 - New Enhancements for Security and Usability - APJEDB
 
Comment sauvegarder correctement vos données
Comment sauvegarder correctement vos donnéesComment sauvegarder correctement vos données
Comment sauvegarder correctement vos donnéesEDB
 
Cloud Native PostgreSQL - Italiano
Cloud Native PostgreSQL - ItalianoCloud Native PostgreSQL - Italiano
Cloud Native PostgreSQL - ItalianoEDB
 
New enhancements for security and usability in EDB 13
New enhancements for security and usability in EDB 13New enhancements for security and usability in EDB 13
New enhancements for security and usability in EDB 13EDB
 
Best Practices in Security with PostgreSQL
Best Practices in Security with PostgreSQLBest Practices in Security with PostgreSQL
Best Practices in Security with PostgreSQLEDB
 
Cloud Native PostgreSQL - APJ
Cloud Native PostgreSQL - APJCloud Native PostgreSQL - APJ
Cloud Native PostgreSQL - APJEDB
 

Plus de EDB (20)

Cloud Migration Paths: Kubernetes, IaaS, or DBaaS
Cloud Migration Paths: Kubernetes, IaaS, or DBaaSCloud Migration Paths: Kubernetes, IaaS, or DBaaS
Cloud Migration Paths: Kubernetes, IaaS, or DBaaS
 
Die 10 besten PostgreSQL-Replikationsstrategien für Ihr Unternehmen
Die 10 besten PostgreSQL-Replikationsstrategien für Ihr UnternehmenDie 10 besten PostgreSQL-Replikationsstrategien für Ihr Unternehmen
Die 10 besten PostgreSQL-Replikationsstrategien für Ihr Unternehmen
 
Migre sus bases de datos Oracle a la nube
Migre sus bases de datos Oracle a la nube Migre sus bases de datos Oracle a la nube
Migre sus bases de datos Oracle a la nube
 
EFM Office Hours - APJ - July 29, 2021
EFM Office Hours - APJ - July 29, 2021EFM Office Hours - APJ - July 29, 2021
EFM Office Hours - APJ - July 29, 2021
 
Benchmarking Cloud Native PostgreSQL
Benchmarking Cloud Native PostgreSQLBenchmarking Cloud Native PostgreSQL
Benchmarking Cloud Native PostgreSQL
 
Las Variaciones de la Replicación de PostgreSQL
Las Variaciones de la Replicación de PostgreSQLLas Variaciones de la Replicación de PostgreSQL
Las Variaciones de la Replicación de PostgreSQL
 
NoSQL and Spatial Database Capabilities using PostgreSQL
NoSQL and Spatial Database Capabilities using PostgreSQLNoSQL and Spatial Database Capabilities using PostgreSQL
NoSQL and Spatial Database Capabilities using PostgreSQL
 
Is There Anything PgBouncer Can’t Do?
Is There Anything PgBouncer Can’t Do?Is There Anything PgBouncer Can’t Do?
Is There Anything PgBouncer Can’t Do?
 
Data Analysis with TensorFlow in PostgreSQL
Data Analysis with TensorFlow in PostgreSQLData Analysis with TensorFlow in PostgreSQL
Data Analysis with TensorFlow in PostgreSQL
 
Practical Partitioning in Production with Postgres
Practical Partitioning in Production with PostgresPractical Partitioning in Production with Postgres
Practical Partitioning in Production with Postgres
 
A Deeper Dive into EXPLAIN
A Deeper Dive into EXPLAINA Deeper Dive into EXPLAIN
A Deeper Dive into EXPLAIN
 
IOT with PostgreSQL
IOT with PostgreSQLIOT with PostgreSQL
IOT with PostgreSQL
 
A Journey from Oracle to PostgreSQL
A Journey from Oracle to PostgreSQLA Journey from Oracle to PostgreSQL
A Journey from Oracle to PostgreSQL
 
Psql is awesome!
Psql is awesome!Psql is awesome!
Psql is awesome!
 
EDB 13 - New Enhancements for Security and Usability - APJ
EDB 13 - New Enhancements for Security and Usability - APJEDB 13 - New Enhancements for Security and Usability - APJ
EDB 13 - New Enhancements for Security and Usability - APJ
 
Comment sauvegarder correctement vos données
Comment sauvegarder correctement vos donnéesComment sauvegarder correctement vos données
Comment sauvegarder correctement vos données
 
Cloud Native PostgreSQL - Italiano
Cloud Native PostgreSQL - ItalianoCloud Native PostgreSQL - Italiano
Cloud Native PostgreSQL - Italiano
 
New enhancements for security and usability in EDB 13
New enhancements for security and usability in EDB 13New enhancements for security and usability in EDB 13
New enhancements for security and usability in EDB 13
 
Best Practices in Security with PostgreSQL
Best Practices in Security with PostgreSQLBest Practices in Security with PostgreSQL
Best Practices in Security with PostgreSQL
 
Cloud Native PostgreSQL - APJ
Cloud Native PostgreSQL - APJCloud Native PostgreSQL - APJ
Cloud Native PostgreSQL - APJ
 

Dernier

"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesZilliz
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 

Dernier (20)

"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector Databases
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 

Processing Data Inside PostgreSQL Using SQL, Functions, Triggers

  • 1. Processing Data Inside PostgreSQL BRUCE MOMJIAN, ENTERPRISEDB February, 2009 Abstract There are indisputable advantages of doing data processing in the database rather than in each application. This presentation explores the ability to push data processing into the database using SQL, functions, triggers, and the object-relational features of POSTGRESQL. Creative Commons Attribution License http://momjian.us/presentations
  • 2. Pre-SQL Data Access No one wants to return to this era: Complex cross-table access   Single index   No optimizer   Simple WHERE processing   No aggregation   Processing Data Inside PostgreSQL 1
  • 3. SQL Data Access You probably take these for granted: Easy cross-table access, with optimizer assistance   Complex WHERE processing   Transaction Control   Concurrency   Portable language (SQL)   Processing Data Inside PostgreSQL 2
  • 4. Post-Ingres Welcome to the next generation of data storage. Processing Data Inside PostgreSQL 3
  • 5. Contents 1. SQL 2. Functions and Triggers 3. Customizing Database Features Processing Data Inside PostgreSQL 4
  • 6. 1. SQL Make full use of the SQL tools available. Processing Data Inside PostgreSQL 5
  • 7. 2. Functions and Triggers Put your programs in the database. Processing Data Inside PostgreSQL 6
  • 8. 3. Customizing Database Features Change the database features. Processing Data Inside PostgreSQL 7
  • 9. 1. SQL Processing Data Inside PostgreSQL 8
  • 10. Table Constraints Table creation requires concentration. Processing Data Inside PostgreSQL 9
  • 11. Unique Test in an Application BEGIN; LOCK tab; SELECT ... WHERE col = key; if not found INSERT (or UPDATE) COMMIT; Processing Data Inside PostgreSQL 10
  • 12. UNIQUE Constraint CREATE TABLE tab ( col ... UNIQUE ); CREATE TABLE customer (id INTEGER UNIQUE); Processing Data Inside PostgreSQL 11
  • 13. Preventing NULLs if (col != NULL) INSERT/UPDATE; Processing Data Inside PostgreSQL 12
  • 14. NOT NULL Constraint CREATE TABLE tab ( col ... NOT NULL ); CREATE TABLE customer (name TEXT NOT NULL); Processing Data Inside PostgreSQL 13
  • 15. Primary Key Constraint UNIQUE   NOT NULL   CREATE TABLE customer (id INTEGER PRIMARY KEY); Processing Data Inside PostgreSQL 14
  • 16. Ensuring Table Linkage Foreign —> Primary BEGIN; SELECT * FROM primary WHERE key = col FOR UPDATE; if found INSERT (or UPDATE) INTO foreign; COMMIT; Processing Data Inside PostgreSQL 15
  • 17. Ensuring Table Linkage Primary —> Foreign BEGIN; SELECT * FROM foreign WHERE col = key FOR UPDATE; if found ? UPDATE/DELETE primary; COMMIT; Processing Data Inside PostgreSQL 16
  • 18. Ensuring Table Linkage Example CREATE TABLE statename ( code CHAR(2) PRIMARY KEY, name VARCHAR(30) ); CREATE TABLE customer ( customer_id INTEGER, name VARCHAR(30), telephone VARCHAR(20), street VARCHAR(40), city VARCHAR(25), state CHAR(2) REFERENCES statename, zipcode CHAR(10), country VARCHAR(20) ); Processing Data Inside PostgreSQL 17
  • 19. Ensuring Table Linkage Larger Example CREATE TABLE customer ( customer_id INTEGER PRIMARY KEY, name VARCHAR(30), telephone VARCHAR(20), street VARCHAR(40), city VARCHAR(25), state CHAR(2), zipcode CHAR(10), country VARCHAR(20) ); CREATE TABLE employee ( employee_id INTEGER PRIMARY KEY, name VARCHAR(30), hire_date DATE ); CREATE TABLE part ( Processing Data Inside PostgreSQL 18
  • 20. part_id INTEGER PRIMARY KEY, name VARCHAR(30), cost NUMERIC(8,2), weight FLOAT ); CREATE TABLE salesorder ( order_id INTEGER, customer_id INTEGER REFERENCES customer, employee_id INTEGER REFERENCES employee, part_id INTEGER REFERENCES part, order_date DATE, ship_date DATE, payment NUMERIC(8,2) ); Processing Data Inside PostgreSQL 19
  • 21. Ensuring Table Linkage Prevent Change to Primary BEGIN; SELECT ... FROM foreign WHERE col = key FOR UPDATE; IF found ABORT; UPDATE/DELETE primary; COMMIT; Processing Data Inside PostgreSQL 20
  • 22. Ensuring Table Linkage REFERENCES Constraint NO ACTION/RESTRICT (default) CREATE TABLE foreign ( col ... REFERENCES primary (col) ON UPDATE NO ACTION -- not required ON DELETE NO ACTION -- not required ); Processing Data Inside PostgreSQL 21
  • 23. Ensuring Table Linkage Cascade Change to Primary BEGIN; SELECT ... FROM foreign WHERE col = key FOR UPDATE; IF found UPDATE/DELETE foreign; UPDATE/DELETE primary; COMMIT; Processing Data Inside PostgreSQL 22
  • 24. Ensuring Table Linkage REFERENCES Constraint CASCADE CREATE TABLE foreign ( col ... REFERENCES primary (col) ON UPDATE CASCADE ON DELETE CASCADE ); Processing Data Inside PostgreSQL 23
  • 25. Ensuring Table Linkage Set Foreign to NULL on Change to Primary BEGIN; SELECT ... FROM foreign WHERE col = key FOR UPDATE; IF found UPDATE foreign SET col = NULL; UPDATE/DELETE primary; COMMIT; Processing Data Inside PostgreSQL 24
  • 26. Ensuring Table Linkage REFERENCES Constraint SET NULL CREATE TABLE foreign ( col ... REFERENCES primary (col) ON UPDATE SET NULL ON DELETE SET NULL ); Processing Data Inside PostgreSQL 25
  • 27. Ensuring Table Linkage Set Foreign to DEFAULT on Change to Primary BEGIN; SELECT ... FROM foreign WHERE col = key FOR UPDATE; IF found UPDATE foreign SET col = DEFAULT; UPDATE/DELETE primary; COMMIT; Processing Data Inside PostgreSQL 26
  • 28. Ensuring Table Linkage REFERENCES Constraint SET DEFAULT CREATE TABLE foreign ( col ... REFERENCES primary (col) ON UPDATE SET DEFAULT ON DELETE SET DEFAULT ); CREATE TABLE order (cust_id INTEGER REFERENCES customer (id)); Processing Data Inside PostgreSQL 27
  • 29. Controlling Data if col > 0 ... (col = 2 OR col = 7) ... length(col) < 10 ... INSERT/UPDATE tab; Processing Data Inside PostgreSQL 28
  • 30. CHECK Constraint CREATE TABLE tab ( col ... CHECK (col > 0 ... ); CREATE TABLE customer (age INTEGER CHECK (age >= 0)); Processing Data Inside PostgreSQL 29
  • 31. Check Constraint Example CREATE TABLE friend2 ( firstname VARCHAR(15), lastname VARCHAR(20), city VARCHAR(15), state CHAR(2) CHECK (length(trim(state)) = 2), age INTEGER CHECK (age >= 0), gender CHAR(1) CHECK (gender IN (’M’,’F’)), last_met DATE CHECK (last_met BETWEEN ’1950-01-01’ AND CURRENT_DATE), CHECK (upper(trim(firstname)) != ’ED’ OR upper(trim(lastname)) != ’RIVERS’) ); INSERT INTO friend2 VALUES (’Ed’, ’Rivers’, ’Wibbleville’, ’J’, -35, ’S’, ’1931-09-23’); ERROR: ExecAppend: rejected due to CHECK constraint friend2_last_met Processing Data Inside PostgreSQL 30
  • 32. Default Column Values if col not specified col = DEFAULT; INSERT/UPDATE tab; Processing Data Inside PostgreSQL 31
  • 33. DEFAULT Constraint CREATE TABLE tab ( quantity ... DEFAULT 1 ); CREATE TABLE customer (created timestamp DEFAULT CURRENT_TIMESTAMP); Processing Data Inside PostgreSQL 32
  • 34. Auto-numbering Column CREATE TABLE counter (curr INTEGER); INSERT INTO counter VALUES (1); ... BEGIN; val = SELECT curr FROM counter FOR UPDATE; UPDATE counter SET curr = curr + 1; COMMIT; INSERT INTO tab VALUES (... val ...); Processing Data Inside PostgreSQL 33
  • 35. SERIAL/Sequence CREATE TABLE tab ( col SERIAL ); CREATE TABLE tab ( col INTEGER DEFAULT nextval(’tab_col_seq’) ); CREATE TABLE customer (id SERIAL); CREATE SEQUENCE customer_id_seq; CREATE TABLE customer (id INTEGER DEFAULT nextval(’customer_id_seq’)); Processing Data Inside PostgreSQL 34
  • 36. Constraint Macros DOMAIN CREATE DOMAIN phone AS CHAR(12) CHECK (VALUE ~ ’^[0-9]{3}-[0-9]{3}-[0-9]{4}$’); CREATE TABLE company ( ... phnum phone, ...); Processing Data Inside PostgreSQL 35
  • 37. Using SELECT’s Features Processing Data Inside PostgreSQL 36
  • 38. ANSI Outer Joins - LEFT OUTER SELECT * FROM tab1, tab2 WHERE tab1.col = tab2.col UNION SELECT * FROM tab1 WHERE col NOT IN ( SELECT tab2.col FROM tab2 ); SELECT * FROM tab1 LEFT JOIN tab2 ON tab1.col = tab2.col; Processing Data Inside PostgreSQL 37
  • 39. ANSI Outer Joins - RIGHT OUTER SELECT * FROM tab1, tab2 WHERE tab1.col = tab2.col UNION SELECT * FROM tab2 WHERE col NOT IN ( SELECT tab1.col FROM tab1 ); SELECT * FROM tab1 RIGHT JOIN tab2 ON tab1.col = tab2.col; Processing Data Inside PostgreSQL 38
  • 40. ANSI Outer Joins - FULL OUTER SELECT * FROM tab1, tab2 WHERE tab1.col = tab2.col UNION SELECT * FROM tab1 WHERE col NOT IN ( SELECT tab2.col FROM tab2 ) UNION SELECT * FROM tab2 WHERE col NOT IN ( SELECT tab1.col FROM tab1 ); SELECT * FROM tab1 FULL JOIN tab2 ON tab1.col = tab2.col; Processing Data Inside PostgreSQL 39
  • 41. ANSI Outer Join Example SELECT * FROM customer LEFT JOIN order ON customer.id = order.cust_id; Processing Data Inside PostgreSQL 40
  • 42. Aggregates SUM() total = 0 FOREACH val IN set total = total + val; END FOREACH SELECT SUM(val) FROM tab; Processing Data Inside PostgreSQL 41
  • 43. Aggregates MAX() max = MIN_VAL; FOREACH val IN set if (val > max) max = val; END FOREACH SELECT MAX(val) FROM tab; SELECT MAX(cost) FROM part; Processing Data Inside PostgreSQL 42
  • 44. Aggregates GROUP BY SUM() qsort(set) save = ’’; total = 0; FOREACH val IN set if val != save and save != ’’ { print save, total; save = val; total = 0; } total = total + amt; END FOREACH if save != ’’ print save, total; SELECT val, SUM(amt) FROM tab GROUP BY val; Processing Data Inside PostgreSQL 43
  • 45. Aggregates GROUP BY MAX() save = ’’; max = MIN_VAL; FOREACH val IN set if val != save and save != ’’ { print save, max; save = val; max = MIN_VAL; } if (amt > max) max = amt; END FOREACH if save != ’’ print save, max; SELECT val, MAX(amt) FROM tab GROUP BY val; Processing Data Inside PostgreSQL 44
  • 46. Aggregates GROUP BY Examples SELECT part, COUNT(*) FROM order ORDER BY part; SELECT cust_id, SUM(due) FROM order GROUP BY cust_id ORDER BY 2 DESC; Processing Data Inside PostgreSQL 45
  • 47. Merging SELECTs UNION SELECT * INTO TEMP out FROM ... INSERT INTO TEMP out SELECT ... INSERT INTO TEMP out SELECT ... SELECT DISTINCT ... SELECT * UNION SELECT * UNION SELECT *; Processing Data Inside PostgreSQL 46
  • 48. Joining SELECTs INTERSECT SELECT * INTO TEMP out; DELETE FROM out WHERE out.* NOT IN (SELECT ...); DELETE FROM out WHERE out.* NOT IN (SELECT ...); SELECT * INTERSECT SELECT * INTERSECT SELECT *; Processing Data Inside PostgreSQL 47
  • 49. Subtracting SELECTs EXCEPT SELECT * INTO TEMP out; DELETE FROM out WHERE out.* IN (SELECT ...); DELETE FROM out WHERE out.* IN (SELECT ...); SELECT * EXCEPT SELECT * EXCEPT SELECT *; Processing Data Inside PostgreSQL 48
  • 50. Controlling Rows Returned LIMIT/OFFSET DECLARE limdemo CURSOR FOR SELECT ... FOR i = 1 to 5 FETCH IN limdemo END FOR SELECT * LIMIT 5; DECLARE limdemo CURSOR FOR SELECT ... MOVE 20 IN limdemo FOR i = 1 to 5 FETCH IN limdemo; END FOR SELECT * OFFSET 20 LIMIT 5; Processing Data Inside PostgreSQL 49
  • 51. Controlling Rows Returned LIMIT/OFFSET Example SELECT order_id, balance FROM order ORDER BY balance DESC LIMIT 10; Processing Data Inside PostgreSQL 50
  • 52. Locking SELECT Rows FOR UPDATE BEGIN; LOCK tab; SELECT * FROM CUSTOMER WHERE id = 4452; UPDATE customer SET balance = 0 WHERE id = 4452; COMMIT; BEGIN; SELECT * FROM customer WHERE id = 4452 FOR UPDATE; ... UPDATE customer SET balance = 0 Processing Data Inside PostgreSQL 51
  • 53. WHERE id = 4452; COMMIT; Processing Data Inside PostgreSQL 52
  • 54. Temporary Tables CREATE TABLE tab (...); ... DROP TABLE tab; CREATE TEMP TABLE tab (...); SELECT * INTO TEMPORARY hold FROM tab1, tab2, tab3 WHERE ... Processing Data Inside PostgreSQL 53
  • 55. Automatically Modify SELECT VIEW - One Column SELECT col4 FROM tab; CREATE VIEW view1 AS SELECT col4 FROM tab; SELECT * FROM view1; Processing Data Inside PostgreSQL 54
  • 56. Automatically Modify SELECT VIEW - One Row SELECT * FROM tab WHERE col = ’ISDN’; CREATE VIEW view2 AS SELECT * FROM tab WHERE col = ’ISDN’; SELECT * FROM view2; Processing Data Inside PostgreSQL 55
  • 57. Automatically Modify SELECT VIEW - One Field SELECT col4 FROM tab WHERE col = ’ISDN’; CREATE VIEW view3 AS SELECT col4 FROM tab WHERE col = ’ISDN’; SELECT * FROM view3; Processing Data Inside PostgreSQL 56
  • 58. Automatically Modify INSERT/UPDATE/DELETE Rules INSERT INTO tab1 VALUES (...); INSERT INTO tab2 VALUES (...); CREATE RULE insert_tab1 AS ON INSERT TO tab1 DO INSERT INTO tab2 VALUES (...); INSERT INTO tab1 VALUES (...); Processing Data Inside PostgreSQL 57
  • 59. Automatically Modify INSERT/UPDATE/DELETE Rules Example CREATE TABLE service_request ( customer_id INTEGER, description text, cre_user text DEFAULT CURRENT_USER, cre_timestamp timestamp DEFAULT CURRENT_TIMESTAMP ); CREATE TABLE service_request_log ( customer_id INTEGER, description text, mod_type char(1), mod_user text DEFAULT CURRENT_USER, mod_timestamp timestamp DEFAULT CURRENT_TIMESTAMP ); Processing Data Inside PostgreSQL 58
  • 60. Rules Example - Rule Definition CREATE RULE service_request_update AS -- UPDATE rule ON UPDATE TO service_request DO INSERT INTO service_request_log (customer_id, description, mod_type) VALUES (old.customer_id, old.description, ’U’); CREATE RULE service_request_delete AS -- DELETE rule ON DELETE TO service_request DO INSERT INTO service_request_log (customer_id, description, mod_type) VALUES (old.customer_id, old.description, ’D’); Processing Data Inside PostgreSQL 59
  • 61. Multi-User Consistency Atomic Changes   Atomic Visibility   Atomic Consistency   Reliability   User 1 User 2 Descrip BEGIN WORK User 1 starts a t UPDATE acct SET balance = balance - 100 WHERE acctno = 53224 remove 100 from UPDATE acct SET balance = balance + 100 WHERE acctno = 94913 add 100 to an a SELECT * FROM acct sees both change SELECT * FROM acct sees no changes COMMIT WORK SELECT * FROM acct sees both change Processing Data Inside PostgreSQL 60
  • 62. Notification LISTEN/NOTIFY signal()/kill() LISTEN myevent; NOTIFY myevent; Processing Data Inside PostgreSQL 61
  • 63. Application Walk-through Gborg, http://gborg.postgresql.org/ Processing Data Inside PostgreSQL 62
  • 64. 2. Functions and Triggers Placing Code Into the Database: Server-side Functions Processing Data Inside PostgreSQL 63
  • 65. Single-Parameter Built-In Functions/Operator SELECT factorial(10); factorial ----------- 3628800 (1 row) SELECT 10!; ?column? ---------- 3628800 (1 row) Processing Data Inside PostgreSQL 64
  • 66. Two-Parameter Built-in Function/Operator SELECT date_mi(’2003-05-20’::date, ’2001-10-13’::date); date_mi --------- 584 (1 row) SELECT ’2003-05-20’::date - ’2001-10-13’::date; ?column? ---------- 584 (1 row) psql df psql do Processing Data Inside PostgreSQL 65
  • 67. Custom Server-Side Functions Create function   Call function, manually or automatically   Processing Data Inside PostgreSQL 66
  • 68. Compute Sales Tax total = cost * 1.06; INSERT ... VALUES ( ... total ... ); INSERT ... VALUES ( ... cost * 1.06, ... ); CREATE FUNCTION total(float) RETURNS float AS ’SELECT $1 * 1.06;’ LANGUAGE ’sql’; INSERT ... VALUES ( ... total(cost) ... ) Processing Data Inside PostgreSQL 67
  • 69. Convert Fahrenheit to Centigrade cent = (faren - 32.0) * 5.0 / 9.0 INSERT ... VALUES ( ... cent ... ) INSERT ... VALUES ( ... (faren - 32.0) * 5.0 / 9.0, ... ) CREATE FUNCTION ftoc(float) RETURNS float AS ’SELECT ($1 - 32.0) * 5.0 / 9.0;’ LANGUAGE ’sql’; INSERT ... VALUES ( ... ftoc(faren) ... ) Processing Data Inside PostgreSQL 68
  • 70. Compute Shipping Cost if cost < 2 shipping = 3.00 else if cost < 4 shipping = 5.00 else shipping = 6.00 INSERT ... VALUES ( ... cost + shipping ... ); Processing Data Inside PostgreSQL 69
  • 71. Shipping Cost Function CREATE FUNCTION shipping(numeric) RETURNS numeric AS ’SELECT CASE WHEN $1 < 2 THEN CAST(3.00 AS numeric(8,2)) WHEN $1 >= 2 AND $1 < 4 THEN CAST(5.00 AS numeric(8,2)) WHEN $1 >= 4 THEN CAST(6.00 AS numeric(8,2)) END;’ LANGUAGE ’sql’; INSERT ... VALUES ( ... cost + shipping(cost) ... ); Processing Data Inside PostgreSQL 70
  • 72. String Processing — PL/pgSQL CREATE FUNCTION spread(text) RETURNS text AS $$ DECLARE str text; ret text; i integer; len integer; BEGIN str := upper($1); ret := ’’; -- start with zero length i := 1; len := length(str); WHILE i <= len LOOP ret := ret || substr(str, i, 1) || ’ ’; i := i + 1; END LOOP; RETURN ret; Processing Data Inside PostgreSQL 71
  • 73. END; $$ LANGUAGE ’plpgsql’; SELECT spread(’Major Financial Report’); spread ---------------------------------------------- M A J O R F I N A N C I A L R E P O R T (1 row) Processing Data Inside PostgreSQL 72
  • 74. State Name Lookup SQL Language Function SELECT name FROM statename WHERE code = ’AL’; CREATE FUNCTION getstatename(text) RETURNS text AS ’SELECT name FROM statename WHERE code = $1;’ LANGUAGE ’sql’; SELECT getstatename(’AL’); Processing Data Inside PostgreSQL 73
  • 75. State Name Lookup From String PL/pgSQL Language Function CREATE FUNCTION getstatecode(text) RETURNS text AS $$ DECLARE state_str statename.name%TYPE; statename_rec record; i integer; len integer; matches record; search_str text; BEGIN state_str := initcap($1); -- capitalization match column len := length(trim($1)); i := 2; SELECT INTO statename_rec * -- first try for an exact match FROM statename WHERE name = state_str; IF FOUND THEN RETURN statename_rec.code; END IF; Processing Data Inside PostgreSQL 74
  • 76. WHILE i <= len LOOP -- test 2,4,6,... chars for match search_str = trim(substr(state_str, 1, i)) || ’%’; SELECT INTO matches COUNT(*) FROM statename WHERE name LIKE search_str; IF matches.count = 0 -- no matches, failure THEN RETURN NULL; END IF; IF matches.count = 1 -- exactly one match, return it THEN SELECT INTO statename_rec * FROM statename WHERE name LIKE search_str; IF FOUND THEN RETURN statename_rec.code; END IF; END IF; i := i + 2; -- >1 match, try 2 more chars END LOOP; RETURN ’’; END; $$ LANGUAGE ’plpgsql’; SELECT getstatecode(’Alabama’); SELECT getstatecode(’ALAB’); Processing Data Inside PostgreSQL 75
  • 77. SELECT getstatecode(’Al’); SELECT getstatecode(’Ail’); Processing Data Inside PostgreSQL 76
  • 78. State Name Maintenance CREATE FUNCTION change_statename(char(2), char(30)) RETURNS boolean AS $$ DECLARE state_code ALIAS FOR $1; state_name ALIAS FOR $2; statename_rec RECORD; BEGIN IF length(state_code) = 0 -- no state code, failure THEN RETURN ’f’; ELSE IF length(state_name) != 0 -- is INSERT or UPDATE? THEN SELECT INTO statename_rec * FROM statename WHERE code = state_code; IF NOT FOUND -- is state not in table? THEN INSERT INTO statename VALUES (state_code, state_name); ELSE UPDATE statename SET name = state_name Processing Data Inside PostgreSQL 77
  • 79. WHERE code = state_code; END IF; RETURN ’t’; ELSE -- is DELETE SELECT INTO statename_rec * FROM statename WHERE code = state_code; IF FOUND THEN DELETE FROM statename WHERE code = state_code; RETURN ’t’; ELSE RETURN ’f’; END IF; END IF; END IF; END; $$ LANGUAGE ’plpgsql’; SELECT change_statename(’AL’,’Alabama’); SELECT change_statename(’AL’,’Bermuda’); SELECT change_statename(’AL’,’’); SELECT change_statename(’AL’,’’); -- row was already deleted Processing Data Inside PostgreSQL 78
  • 80. SELECT Inside FROM SELECT * FROM (SELECT * FROM tab) AS tab; SELECT * FROM ( SELECT 1,2,3,4,5 UNION SELECT 6,7,8,9,10 UNION SELECT 11,12,13,14,15) AS tab15; col| col| col| col| col ---+----+----+----+---- 1 | 2 | 3 | 4 | 5 6 | 7 | 8 | 9 | 10 11 | 12 | 13 | 14 | 15 (3 rows) Processing Data Inside PostgreSQL 79
  • 81. Function Returning Multiple Values CREATE TABLE int5(x1 INTEGER, x2 INTEGER, x3 INTEGER, x4 INTE- GER, x5 INTEGER); CREATE FUNCTION func5() RETURNS SETOF int5 AS ’SELECT 1,2,3,4,5;’ LANGUAGE SQL; SELECT * FROM func5(); x1 | x2 | x3 | x4 | x5 ----+----+----+----+---- 1 | 2 | 3 | 4 | 5 (1 row) Processing Data Inside PostgreSQL 80
  • 82. Function Returning a Table Result CREATE OR REPLACE FUNCTION func15() RETURNS SETOF int5 AS ’ SELECT 1,2,3,4,5 UNION SELECT 6,7,8,9,10 UNION SELECT 11,12,13,14,15;’ LANGUAGE SQL; SELECT * FROM func15(); x1 | x2 | x3 | x4 | x5 ----+----+----+----+---- 1 | 2 | 3 | 4 | 5 6 | 7 | 8 | 9 | 10 11 | 12 | 13 | 14 | 15 (3 rows) Processing Data Inside PostgreSQL 81
  • 83. Automatic Function Calls Trigger BEFORE/AFTER ROW   INSERT/UPDATE/DELETE   OLD/NEW   Processing Data Inside PostgreSQL 82
  • 84. Trigger on Statename CREATE FUNCTION trigger_insert_update_statename() RETURNS trigger AS $$ BEGIN IF new.code !~ ’^[A-Za-z][A-Za-z]$’ THEN RAISE EXCEPTION ’State code must be two alphabetic characters.’; END IF; IF new.name !~ ’^[A-Za-z ]*$’ THEN RAISE EXCEPTION ’State name must be only alphabetic characters.’; END IF; IF length(trim(new.name)) < 3 THEN RAISE EXCEPTION ’State name must longer than two characters.’; END IF; new.code = upper(new.code); -- uppercase statename.code new.name = initcap(new.name); -- capitalize statename.name RETURN new; END; $$ Processing Data Inside PostgreSQL 83
  • 86. Install Trigger On Statename CREATE TRIGGER trigger_statename BEFORE INSERT OR UPDATE ON statename FOR EACH ROW EXECUTE PROCEDURE trigger_insert_update_statename(); INSERT INTO statename VALUES (’a’, ’alabama’); INSERT INTO statename VALUES (’al’, ’alabama2’); INSERT INTO statename VALUES (’al’, ’al’); INSERT INTO statename VALUES (’al’, ’alabama’); Processing Data Inside PostgreSQL 85
  • 87. Function Languages SQL   PL/pgSQL   PL/TCL   PL/Python   PL/Perl   PL/sh   C   Processing Data Inside PostgreSQL 86
  • 88. Function Examples /contrib/earthdistance   /contrib/fuzzystringmatch   /contrib/pgcrypto   Processing Data Inside PostgreSQL 87
  • 89. 3. Customizing Database Features Adding New Data and Indexing Features Processing Data Inside PostgreSQL 88
  • 90. Creation CREATE FUNCTIONS in C   CREATE TYPE   CREATE OPERATOR   CREATE OPERATOR CLASS (index type)   Processing Data Inside PostgreSQL 89
  • 91. Create New Data Type With Operator and Index Support Write input/output functions   Register input/output functions with CREATE FUNCTION   Register type with CREATE TYPE   Write comparison functions   Register comparison functions with CREATE FUNCTION   Register comparison functions with CREATE OPERATOR   Register operator class for indexes with CREATE OPERATOR CLASS   Processing Data Inside PostgreSQL 90
  • 92. Create New Data Type Examples /contrib/chkpass   /contrib/isn   /contrib/cube   /contrib/ltree   /src/backend/utils/adt   Processing Data Inside PostgreSQL 91