Category: postgresql

  • Khóa học miễn phí Date/Time Functions & Operators nhận dự án làm có lương

    PostgreSQL – DATE/TIME Functions and Operators



    We had discussed about the Date/Time data types in the chapter . Now, let us see the Date/Time operators and Functions.

    The following table lists the behaviors of the basic arithmetic operators −

    Operator Example Result
    + date ”2001-09-28” + integer ”7” date ”2001-10-05”
    + date ”2001-09-28” + interval ”1 hour” timestamp ”2001-09-28 01:00:00”
    + date ”2001-09-28” + time ”03:00” timestamp ”2001-09-28 03:00:00”
    + interval ”1 day” + interval ”1 hour” interval ”1 day 01:00:00”
    + timestamp ”2001-09-28 01:00” + interval ”23 hours” timestamp ”2001-09-29 00:00:00”
    + time ”01:00” + interval ”3 hours” time ”04:00:00”
    – interval ”23 hours” interval ”-23:00:00”
    date ”2001-10-01” – date ”2001-09-28” integer ”3” (days)
    date ”2001-10-01” – integer ”7” date ”2001-09-24”
    date ”2001-09-28” – interval ”1 hour” timestamp ”2001-09-27 23:00:00”
    time ”05:00” – time ”03:00” interval ”02:00:00”
    time ”05:00” – interval ”2 hours” time ”03:00:00”
    timestamp ”2001-09-28 23:00” – interval ”23 hours” timestamp ”2001-09-28 00:00:00”
    interval ”1 day” – interval ”1 hour” interval ”1 day -01:00:00”
    timestamp ”2001-09-29 03:00” – timestamp ”2001-09-27 12:00” interval ”1 day 15:00:00”
    * 900 * interval ”1 second” interval ”00:15:00”
    * 21 * interval ”1 day” interval ”21 days”
    * double precision ”3.5” * interval ”1 hour” interval ”03:30:00”
    / interval ”1 hour” / double precision ”1.5” interval ”00:40:00”

    The following is the list of all important Date and Time related functions available.

    S. No. Function & Description
    1

    Subtract arguments

    2

    Current date and time

    3

    Get subfield (equivalent to extract)

    4

    Get subfield

    5

    Test for finite date, time and interval (not +/-infinity)

    6

    Adjust interval

    AGE(timestamp, timestamp), AGE(timestamp)

    S. No. Function & Description
    1

    AGE(timestamp, timestamp)

    When invoked with the TIMESTAMP form of the second argument, AGE() subtract arguments, producing a “symbolic” result that uses years and months and is of type INTERVAL.

    2

    AGE(timestamp)

    When invoked with only the TIMESTAMP as argument, AGE() subtracts from the current_date (at midnight).

    Example of the function AGE(timestamp, timestamp) is −

    testdb=# SELECT AGE(timestamp ''2001-04-10'', timestamp ''1957-06-13'');
    

    The above given PostgreSQL statement will produce the following result −

               age
    -------------------------
     43 years 9 mons 27 days
    

    Example of the function AGE(timestamp) is −

    testdb=# select age(timestamp ''1957-06-13'');
    

    The above given PostgreSQL statement will produce the following result −

               age
    --------------------------
     55 years 10 mons 22 days
    

    CURRENT DATE/TIME()

    PostgreSQL provides a number of functions that return values related to the current date and time. Following are some functions −

    S. No. Function & Description
    1

    CURRENT_DATE

    Delivers current date.

    2

    CURRENT_TIME

    Delivers values with time zone.

    3

    CURRENT_TIMESTAMP

    Delivers values with time zone.

    4

    CURRENT_TIME(precision)

    Optionally takes a precision parameter, which causes the result to be rounded to that many fractional digits in the seconds field.

    5

    CURRENT_TIMESTAMP(precision)

    Optionally takes a precision parameter, which causes the result to be rounded to that many fractional digits in the seconds field.

    6

    LOCALTIME

    Delivers values without time zone.

    7

    LOCALTIMESTAMP

    Delivers values without time zone.

    8

    LOCALTIME(precision)

    Optionally takes a precision parameter, which causes the result to be rounded to that many fractional digits in the seconds field.

    9

    LOCALTIMESTAMP(precision)

    Optionally takes a precision parameter, which causes the result to be rounded to that many fractional digits in the seconds field.

    Examples using the functions from the table above −

    testdb=# SELECT CURRENT_TIME;
           timetz
    --------------------
     08:01:34.656+05:30
    (1 row)
    
    
    testdb=# SELECT CURRENT_DATE;
        date
    ------------
     2013-05-05
    (1 row)
    
    
    testdb=# SELECT CURRENT_TIMESTAMP;
                  now
    -------------------------------
     2013-05-05 08:01:45.375+05:30
    (1 row)
    
    
    testdb=# SELECT CURRENT_TIMESTAMP(2);
             timestamptz
    ------------------------------
     2013-05-05 08:01:50.89+05:30
    (1 row)
    
    
    testdb=# SELECT LOCALTIMESTAMP;
           timestamp
    ------------------------
     2013-05-05 08:01:55.75
    (1 row)
    

    PostgreSQL also provides functions that return the start time of the current statement, as well as the actual current time at the instant the function is called. These functions are −

    S. No. Function & Description
    1

    transaction_timestamp()

    It is equivalent to CURRENT_TIMESTAMP, but is named to clearly reflect what it returns.

    2

    statement_timestamp()

    It returns the start time of the current statement.

    3

    clock_timestamp()

    It returns the actual current time, and therefore its value changes even within a single SQL command.

    4

    timeofday()

    It returns the actual current time, but as a formatted text string rather than a timestamp with time zone value.

    5

    now()

    It is a traditional PostgreSQL equivalent to transaction_timestamp().

    DATE_PART(text, timestamp), DATE_PART(text, interval), DATE_TRUNC(text, timestamp)

    S. No. Function & Description
    1

    DATE_PART(”field”, source)

    These functions get the subfields. The field parameter needs to be a string value, not a name.

    The valid field names are: century, day, decade, dow, doy, epoch, hour, isodow, isoyear, microseconds, millennium, milliseconds, minute, month, quarter, second, timezone, timezone_hour, timezone_minute, week, year.

    2

    DATE_TRUNC(”field”, source)

    This function is conceptually similar to the trunc function for numbers. source is a value expression of type timestamp or interval. field selects to which precision to truncate the input value. The return value is of type timestamp or interval.

    The valid values for field are : microseconds, milliseconds, second, minute, hour, day, week, month, quarter, year, decade, century, millennium

    The following are examples for DATE_PART(”field”, source) functions −

    testdb=# SELECT date_part(''day'', TIMESTAMP ''2001-02-16 20:38:40'');
     date_part
    -----------
            16
    (1 row)
    
    
    testdb=# SELECT date_part(''hour'', INTERVAL ''4 hours 3 minutes'');
     date_part
    -----------
             4
    (1 row)
    

    The following are examples for DATE_TRUNC(”field”, source) functions −

    testdb=# SELECT date_trunc(''hour'', TIMESTAMP ''2001-02-16 20:38:40'');
         date_trunc
    ---------------------
     2001-02-16 20:00:00
    (1 row)
    
    
    testdb=# SELECT date_trunc(''year'', TIMESTAMP ''2001-02-16 20:38:40'');
         date_trunc
    ---------------------
     2001-01-01 00:00:00
    (1 row)
    

    EXTRACT(field from timestamp), EXTRACT(field from interval)

    The EXTRACT(field FROM source) function retrieves subfields such as year or hour from date/time values. The source must be a value expression of type timestamp, time, or interval. The field is an identifier or string that selects what field to extract from the source value. The EXTRACT function returns values of type double precision.

    The following are valid field names (similar to DATE_PART function field names): century, day, decade, dow, doy, epoch, hour, isodow, isoyear, microseconds, millennium, milliseconds, minute, month, quarter, second, timezone, timezone_hour, timezone_minute, week, year.

    The following are examples of EXTRACT(”field”, source) functions −

    testdb=# SELECT EXTRACT(CENTURY FROM TIMESTAMP ''2000-12-16 12:21:13'');
     date_part
    -----------
            20
    (1 row)
    
    
    testdb=# SELECT EXTRACT(DAY FROM TIMESTAMP ''2001-02-16 20:38:40'');
     date_part
    -----------
            16
    (1 row)
    

    ISFINITE(date), ISFINITE(timestamp), ISFINITE(interval)

    S. No. Function & Description
    1

    ISFINITE(date)

    Tests for finite date.

    2

    ISFINITE(timestamp)

    Tests for finite time stamp.

    3

    ISFINITE(interval)

    Tests for finite interval.

    The following are the examples of the ISFINITE() functions −

    testdb=# SELECT isfinite(date ''2001-02-16'');
     isfinite
    ----------
     t
    (1 row)
    
    
    testdb=# SELECT isfinite(timestamp ''2001-02-16 21:28:30'');
     isfinite
    ----------
     t
    (1 row)
    
    
    testdb=# SELECT isfinite(interval ''4 hours'');
     isfinite
    ----------
     t
    (1 row)
    

    JUSTIFY_DAYS(interval), JUSTIFY_HOURS(interval), JUSTIFY_INTERVAL(interval)

    S. No. Function & Description
    1

    JUSTIFY_DAYS(interval)

    Adjusts interval so 30-day time periods are represented as months. Return the interval type

    2

    JUSTIFY_HOURS(interval)

    Adjusts interval so 24-hour time periods are represented as days. Return the interval type

    3

    JUSTIFY_INTERVAL(interval)

    Adjusts interval using JUSTIFY_DAYS and JUSTIFY_HOURS, with additional sign adjustments. Return the interval type

    The following are the examples for the ISFINITE() functions −

    testdb=# SELECT justify_days(interval ''35 days'');
     justify_days
    --------------
     1 mon 5 days
    (1 row)
    
    
    testdb=# SELECT justify_hours(interval ''27 hours'');
     justify_hours
    ----------------
     1 day 03:00:00
    (1 row)
    
    
    testdb=# SELECT justify_interval(interval ''1 mon -1 hour'');
     justify_interval
    ------------------
     29 days 23:00:00
    (1 row)
    

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí PostgreSQL – Functions nhận dự án làm có lương

    PostgreSQL – Functions



    PostgreSQL functions, also known as Stored Procedures, allow you to carry out operations that would normally take several queries and round trips in a single function within the database. Functions allow database reuse as other applications can interact directly with your stored procedures instead of a middle-tier or duplicating code.

    Functions can be created in a language of your choice like SQL, PL/pgSQL, C, Python, etc.

    Syntax

    The basic syntax to create a function is as follows −

    CREATE [OR REPLACE] FUNCTION function_name (arguments)
    RETURNS return_datatype AS $variable_name$
       DECLARE
          declaration;
          [...]
       BEGIN
          < function_body >
          [...]
          RETURN { variable_name | value }
       END; LANGUAGE plpgsql;
    

    Where,

    • function-name specifies the name of the function.

    • [OR REPLACE] option allows modifying an existing function.

    • The function must contain a return statement.

    • RETURN clause specifies that data type you are going to return from the function. The return_datatype can be a base, composite, or domain type, or can reference the type of a table column.

    • function-body contains the executable part.

    • The AS keyword is used for creating a standalone function.

    • plpgsql is the name of the language that the function is implemented in. Here, we use this option for PostgreSQL, it Can be SQL, C, internal, or the name of a user-defined procedural language. For backward compatibility, the name can be enclosed by single quotes.

    Example

    The following example illustrates creating and calling a standalone function. This function returns the total number of records in the COMPANY table. We will use the table, which has the following records −

    testdb# select * from COMPANY;
     id | name  | age | address   | salary
    ----+-------+-----+-----------+--------
      1 | Paul  |  32 | California|  20000
      2 | Allen |  25 | Texas     |  15000
      3 | Teddy |  23 | Norway    |  20000
      4 | Mark  |  25 | Rich-Mond |  65000
      5 | David |  27 | Texas     |  85000
      6 | Kim   |  22 | South-Hall|  45000
      7 | James |  24 | Houston   |  10000
    (7 rows)
    

    Function totalRecords() is as follows −

    CREATE OR REPLACE FUNCTION totalRecords ()
    RETURNS integer AS $total$
    declare
    	total integer;
    BEGIN
       SELECT count(*) into total FROM COMPANY;
       RETURN total;
    END;
    $total$ LANGUAGE plpgsql;
    

    When the above query is executed, the result would be −

    testdb# CREATE FUNCTION
    

    Now, let us execute a call to this function and check the records in the COMPANY table

    testdb=# select totalRecords();
    

    When the above query is executed, the result would be −

     totalrecords
    --------------
          7
    (1 row)
    

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí PostgreSQL – Useful Functions nhận dự án làm có lương

    PostgreSQL – Useful Functions



    PostgreSQL built-in functions, also called as Aggregate functions, are used for performing processing on string or numeric data.

    The following is the list of all general-purpose PostgreSQL built-in functions −

    • − The PostgreSQL COUNT aggregate function is used to count the number of rows in a database table.

    • − The PostgreSQL MAX aggregate function allows us to select the highest (maximum) value for a certain column.

    • − The PostgreSQL MIN aggregate function allows us to select the lowest (minimum) value for a certain column.

    • − The PostgreSQL AVG aggregate function selects the average value for certain table column.

    • − The PostgreSQL SUM aggregate function allows selecting the total for a numeric column.

    • − The PostgreSQL ARRAY aggregate function puts input values, including nulls, concatenated into an array.

    • − Complete list of PostgreSQL functions required to manipulate numbers in SQL.

    • − Complete list of PostgreSQL functions required to manipulate strings in PostgreSQL.


    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí PostgreSQL – Perl nhận dự án làm có lương

    PostgreSQL – Perl Interface



    Installation

    The PostgreSQL can be integrated with Perl using Perl DBI module, which is a database access module for the Perl programming language. It defines a set of methods, variables and conventions that provide a standard database interface.

    Here are simple steps to install DBI module on your Linux/Unix machine −

    $ wget http://search.cpan.org/CPAN/authors/id/T/TI/TIMB/DBI-1.625.tar.gz
    $ tar xvfz DBI-1.625.tar.gz
    $ cd DBI-1.625
    $ perl Makefile.PL
    $ make
    $ make install
    

    If you need to install SQLite driver for DBI, then it can be installed as follows −

    $ wget http://search.cpan.org/CPAN/authors/id/T/TU/TURNSTEP/DBD-Pg-2.19.3.tar.gz
    $ tar xvfz DBD-Pg-2.19.3.tar.gz
    $ cd DBD-Pg-2.19.3
    $ perl Makefile.PL
    $ make
    $ make install
    

    Before you start using Perl PostgreSQL interface, find the pg_hba.conf file in your PostgreSQL installation directory and add the following line −

    # IPv4 local connections:
    host    all         all         127.0.0.1/32          md5
    

    You can start/restart the postgres server, in case it is not running, using the following command −

    [root@host]# service postgresql restart
    Stopping postgresql service:                               [  OK  ]
    Starting postgresql service:                               [  OK  ]
    

    DBI Interface APIs

    Following are the important DBI routines, which can suffice your requirement to work with SQLite database from your Perl program. If you are looking for a more sophisticated application, then you can look into Perl DBI official documentation.

    S. No. API & Description
    1

    DBI→connect($data_source, “userid”, “password”, %attr)

    Establishes a database connection, or session, to the requested $data_source. Returns a database handle object if the connection succeeds.

    Datasource has the form like : DBI:Pg:dbname=$database;host=127.0.0.1;port=5432 Pg is PostgreSQL driver name and testdb is the name of database.

    2

    $dbh→do($sql)

    This routine prepares and executes a single SQL statement. Returns the number of rows affected or undef on error. A return value of -1 means the number of rows is not known, not applicable, or not available. Here $dbh is a handle returned by DBI→connect() call.

    3

    $dbh→prepare($sql)

    This routine prepares a statement for later execution by the database engine and returns a reference to a statement handle object.

    4

    $sth→execute()

    This routine performs whatever processing is necessary to execute the prepared statement. An undef is returned if an error occurs. A successful execute always returns true regardless of the number of rows affected. Here $sth is a statement handle returned by $dbh→prepare($sql) call.

    5

    $sth→fetchrow_array()

    This routine fetches the next row of data and returns it as a list containing the field values. Null fields are returned as undef values in the list.

    6

    $DBI::err

    This is equivalent to $h→err, where $h is any of the handle types like $dbh, $sth, or $drh. This returns native database engine error code from the last driver method called.

    7

    $DBI::errstr

    This is equivalent to $h→errstr, where $h is any of the handle types like $dbh, $sth, or $drh. This returns the native database engine error message from the last DBI method called.

    8

    $dbh->disconnect()

    This routine closes a database connection previously opened by a call to DBI→connect().

    Connecting to Database

    The following Perl code shows how to connect to an existing database. If the database does not exist, then it will be created and finally a database object will be returned.

    #!/usr/bin/perl
    
    use DBI;
    use strict;
    
    my $driver  = "Pg";
    my $database = "testdb";
    my $dsn = "DBI:$driver:dbname = $database;host = 127.0.0.1;port = 5432";
    my $userid = "postgres";
    my $password = "pass123";
    my $dbh = DBI->connect($dsn, $userid, $password, { RaiseError => 1 })
       or die $DBI::errstr;
    
    print "Opened database successfullyn";
    

    Now, let us run the above given program to open our database testdb; if the database is successfully opened then it will give the following message −

    Open database successfully
    

    Create a Table

    The following Perl program will be used to create a table in previously created database −

    #!/usr/bin/perl
    
    use DBI;
    use strict;
    
    my $driver   = "Pg";
    my $database = "testdb";
    my $dsn = "DBI:$driver:dbname=$database;host=127.0.0.1;port=5432";
    my $userid = "postgres";
    my $password = "pass123";
    my $dbh = DBI->connect($dsn, $userid, $password, { RaiseError => 1 })
       or die $DBI::errstr;
    print "Opened database successfullyn";
    
    my $stmt = qq(CREATE TABLE COMPANY
          (ID INT PRIMARY KEY     NOT NULL,
          NAME           TEXT    NOT NULL,
          AGE            INT     NOT NULL,
          ADDRESS        CHAR(50),
          SALARY         REAL););
    my $rv = $dbh->do($stmt);
    if($rv < 0) {
       print $DBI::errstr;
    } else {
       print "Table created successfullyn";
    }
    $dbh->disconnect();
    

    When the above given program is executed, it will create COMPANY table in your testdb and it will display the following messages −

    Opened database successfully
    Table created successfully
    

    INSERT Operation

    The following Perl program shows how we can create records in our COMPANY table created in above example −

    #!/usr/bin/perl
    
    use DBI;
    use strict;
    
    my $driver   = "Pg";
    my $database = "testdb";
    my $dsn = "DBI:$driver:dbname = $database;host = 127.0.0.1;port = 5432";
    my $userid = "postgres";
    my $password = "pass123";
    my $dbh = DBI->connect($dsn, $userid, $password, { RaiseError => 1 })
       or die $DBI::errstr;
    print "Opened database successfullyn";
    
    my $stmt = qq(INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)
       VALUES (1, ''Paul'', 32, ''California'', 20000.00 ));
    my $rv = $dbh->do($stmt) or die $DBI::errstr;
    
    $stmt = qq(INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)
       VALUES (2, ''Allen'', 25, ''Texas'', 15000.00 ));
    $rv = $dbh->do($stmt) or die $DBI::errstr;
    
    $stmt = qq(INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)
       VALUES (3, ''Teddy'', 23, ''Norway'', 20000.00 ));
    $rv = $dbh->do($stmt) or die $DBI::errstr;
    
    $stmt = qq(INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)
       VALUES (4, ''Mark'', 25, ''Rich-Mond '', 65000.00 ););
    $rv = $dbh->do($stmt) or die $DBI::errstr;
    
    print "Records created successfullyn";
    $dbh->disconnect();
    

    When the above given program is executed, it will create given records in COMPANY table and will display the following two lines −

    Opened database successfully
    Records created successfully
    

    SELECT Operation

    The following Perl program shows how we can fetch and display records from our COMPANY table created in above example −

    #!/usr/bin/perl
    
    use DBI;
    use strict;
    
    my $driver   = "Pg";
    my $database = "testdb";
    my $dsn = "DBI:$driver:dbname = $database;host = 127.0.0.1;port = 5432";
    my $userid = "postgres";
    my $password = "pass123";
    my $dbh = DBI->connect($dsn, $userid, $password, { RaiseError => 1 })
       or die $DBI::errstr;
    print "Opened database successfullyn";
    
    my $stmt = qq(SELECT id, name, address, salary  from COMPANY;);
    my $sth = $dbh->prepare( $stmt );
    my $rv = $sth->execute() or die $DBI::errstr;
    if($rv < 0) {
       print $DBI::errstr;
    }
    while(my @row = $sth->fetchrow_array()) {
          print "ID = ". $row[0] . "n";
          print "NAME = ". $row[1] ."n";
          print "ADDRESS = ". $row[2] ."n";
          print "SALARY =  ". $row[3] ."nn";
    }
    print "Operation done successfullyn";
    $dbh->disconnect();
    

    When the above given program is executed, it will produce the following result −

    Opened database successfully
    ID = 1
    NAME = Paul
    ADDRESS = California
    SALARY =  20000
    
    ID = 2
    NAME = Allen
    ADDRESS = Texas
    SALARY =  15000
    
    ID = 3
    NAME = Teddy
    ADDRESS = Norway
    SALARY =  20000
    
    ID = 4
    NAME = Mark
    ADDRESS = Rich-Mond
    SALARY =  65000
    
    Operation done successfully
    

    UPDATE Operation

    The following Perl code shows how we can use the UPDATE statement to update any record and then fetch and display updated records from our COMPANY table −

    #!/usr/bin/perl
    
    use DBI;
    use strict;
    
    my $driver   = "Pg";
    my $database = "testdb";
    my $dsn = "DBI:$driver:dbname = $database;host = 127.0.0.1;port = 5432";
    my $userid = "postgres";
    my $password = "pass123";
    my $dbh = DBI->connect($dsn, $userid, $password, { RaiseError => 1 })
       or die $DBI::errstr;
    print "Opened database successfullyn";
    
    my $stmt = qq(UPDATE COMPANY set SALARY = 25000.00 where ID=1;);
    my $rv = $dbh->do($stmt) or die $DBI::errstr;
    if( $rv < 0 ) {
       print $DBI::errstr;
    }else{
       print "Total number of rows updated : $rvn";
    }
    $stmt = qq(SELECT id, name, address, salary  from COMPANY;);
    my $sth = $dbh->prepare( $stmt );
    $rv = $sth->execute() or die $DBI::errstr;
    if($rv < 0) {
       print $DBI::errstr;
    }
    while(my @row = $sth->fetchrow_array()) {
          print "ID = ". $row[0] . "n";
          print "NAME = ". $row[1] ."n";
          print "ADDRESS = ". $row[2] ."n";
          print "SALARY =  ". $row[3] ."nn";
    }
    print "Operation done successfullyn";
    $dbh->disconnect();
    

    When the above given program is executed, it will produce the following result −

    Opened database successfully
    Total number of rows updated : 1
    ID = 1
    NAME = Paul
    ADDRESS = California
    SALARY =  25000
    
    ID = 2
    NAME = Allen
    ADDRESS = Texas
    SALARY =  15000
    
    ID = 3
    NAME = Teddy
    ADDRESS = Norway
    SALARY =  20000
    
    ID = 4
    NAME = Mark
    ADDRESS = Rich-Mond
    SALARY =  65000
    
    Operation done successfully
    

    DELETE Operation

    The following Perl code shows how we can use the DELETE statement to delete any record and then fetch and display the remaining records from our COMPANY table −

    #!/usr/bin/perl
    
    use DBI;
    use strict;
    
    my $driver   = "Pg";
    my $database = "testdb";
    my $dsn = "DBI:$driver:dbname = $database;host = 127.0.0.1;port = 5432";
    my $userid = "postgres";
    my $password = "pass123";
    my $dbh = DBI->connect($dsn, $userid, $password, { RaiseError => 1 })
       or die $DBI::errstr;
    print "Opened database successfullyn";
    
    my $stmt = qq(DELETE from COMPANY where ID=2;);
    my $rv = $dbh->do($stmt) or die $DBI::errstr;
    if( $rv < 0 ) {
       print $DBI::errstr;
    } else{
       print "Total number of rows deleted : $rvn";
    }
    $stmt = qq(SELECT id, name, address, salary  from COMPANY;);
    my $sth = $dbh->prepare( $stmt );
    $rv = $sth->execute() or die $DBI::errstr;
    if($rv < 0) {
       print $DBI::errstr;
    }
    while(my @row = $sth->fetchrow_array()) {
          print "ID = ". $row[0] . "n";
          print "NAME = ". $row[1] ."n";
          print "ADDRESS = ". $row[2] ."n";
          print "SALARY =  ". $row[3] ."nn";
    }
    print "Operation done successfullyn";
    $dbh->disconnect();
    

    When the above given program is executed, it will produce the following result −

    Opened database successfully
    Total number of rows deleted : 1
    ID = 1
    NAME = Paul
    ADDRESS = California
    SALARY =  25000
    
    ID = 3
    NAME = Teddy
    ADDRESS = Norway
    SALARY =  20000
    
    ID = 4
    NAME = Mark
    ADDRESS = Rich-Mond
    SALARY =  65000
    
    Operation done successfully
    

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí PostgreSQL – Java nhận dự án làm có lương

    PostgreSQL – JAVA Interface



    Installation

    Before we start using PostgreSQL in our Java programs, we need to make sure that we have PostgreSQL JDBC and Java set up on the machine. You can check Java tutorial for Java installation on your machine. Now let us check how to set up PostgreSQL JDBC driver.

    • Download the latest version of postgresql-(VERSION).jdbc.jar from repository.

    • Add downloaded jar file postgresql-(VERSION).jdbc.jar in your class path, or you can use it along with -classpath option as explained below in the examples.

    The following section assumes you have little knowledge about Java JDBC concepts. If you do not have, then it is suggested to spent half and hour with to become comfortable with concepts explained below.

    Connecting To Database

    The following Java code shows how to connect to an existing database. If the database does not exist, then it will be created and finally a database object will be returned.

    import java.sql.Connection;
    import java.sql.DriverManager;
    
    public class PostgreSQLJDBC {
       public static void main(String args[]) {
          Connection c = null;
          try {
             Class.forName("org.postgresql.Driver");
             c = DriverManager
                .getConnection("jdbc:postgresql://localhost:5432/testdb",
                "postgres", "123");
          } catch (Exception e) {
             e.printStackTrace();
             System.err.println(e.getClass().getName()+": "+e.getMessage());
             System.exit(0);
          }
          System.out.println("Opened database successfully");
       }
    }
    

    Before you compile and run above program, find pg_hba.conf file in your PostgreSQL installation directory and add the following line −

    # IPv4 local connections:
    host    all         all         127.0.0.1/32          md5
    

    You can start/restart the postgres server in case it is not running using the following command −

    [root@host]# service postgresql restart
    Stopping postgresql service:                               [  OK  ]
    Starting postgresql service:                               [  OK  ]
    

    Now, let us compile and run the above program to connect with testdb. Here, we are using postgres as user ID and 123 as password to access the database. You can change this as per your database configuration and setup. We are also assuming current version of JDBC driver postgresql-9.2-1002.jdbc3.jar is available in the current path.

    C:JavaPostgresIntegration>javac PostgreSQLJDBC.java
    C:JavaPostgresIntegration>java -cp c:toolspostgresql-9.2-1002.jdbc3.jar;C:JavaPostgresIntegration PostgreSQLJDBC
    Open database successfully
    

    Create a Table

    The following Java program will be used to create a table in previously opened database. Make sure you do not have this table already in your target database.

    import java.sql.*;
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.Statement;
    
    
    public class PostgreSQLJDBC {
       public static void main( String args[] ) {
          Connection c = null;
          Statement stmt = null;
          try {
             Class.forName("org.postgresql.Driver");
             c = DriverManager
                .getConnection("jdbc:postgresql://localhost:5432/testdb",
                "manisha", "123");
             System.out.println("Opened database successfully");
    
             stmt = c.createStatement();
             String sql = "CREATE TABLE COMPANY " +
                "(ID INT PRIMARY KEY     NOT NULL," +
                " NAME           TEXT    NOT NULL, " +
                " AGE            INT     NOT NULL, " +
                " ADDRESS        CHAR(50), " +
                " SALARY         REAL)";
             stmt.executeUpdate(sql);
             stmt.close();
             c.close();
          } catch ( Exception e ) {
             System.err.println( e.getClass().getName()+": "+ e.getMessage() );
             System.exit(0);
          }
          System.out.println("Table created successfully");
       }
    }
    

    When a program is compiled and executed, it will create the COMPANY table in testdb database and will display the following two lines −

    Opened database successfully
    Table created successfully
    

    INSERT Operation

    The following Java program shows how we can create records in our COMPANY table created in above example −

    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.Statement;
    
    public class PostgreSQLJDBC {
       public static void main(String args[]) {
          Connection c = null;
          Statement stmt = null;
          try {
             Class.forName("org.postgresql.Driver");
             c = DriverManager
                .getConnection("jdbc:postgresql://localhost:5432/testdb",
                "manisha", "123");
             c.setAutoCommit(false);
             System.out.println("Opened database successfully");
    
             stmt = c.createStatement();
             String sql = "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) "
                + "VALUES (1, ''Paul'', 32, ''California'', 20000.00 );";
             stmt.executeUpdate(sql);
    
             sql = "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) "
                + "VALUES (2, ''Allen'', 25, ''Texas'', 15000.00 );";
             stmt.executeUpdate(sql);
    
             sql = "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) "
                + "VALUES (3, ''Teddy'', 23, ''Norway'', 20000.00 );";
             stmt.executeUpdate(sql);
    
             sql = "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) "
                + "VALUES (4, ''Mark'', 25, ''Rich-Mond '', 65000.00 );";
             stmt.executeUpdate(sql);
    
             stmt.close();
             c.commit();
             c.close();
          } catch (Exception e) {
             System.err.println( e.getClass().getName()+": "+ e.getMessage() );
             System.exit(0);
          }
          System.out.println("Records created successfully");
       }
    }
    

    When the above program is compiled and executed, it will create given records in COMPANY table and will display the following two lines −

    Opened database successfully
    Records created successfully
    

    SELECT Operation

    The following Java program shows how we can fetch and display records from our COMPANY table created in above example −

    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.Statement;
    
    
    public class PostgreSQLJDBC {
       public static void main( String args[] ) {
          Connection c = null;
          Statement stmt = null;
          try {
             Class.forName("org.postgresql.Driver");
             c = DriverManager
                .getConnection("jdbc:postgresql://localhost:5432/testdb",
                "manisha", "123");
             c.setAutoCommit(false);
             System.out.println("Opened database successfully");
    
             stmt = c.createStatement();
             ResultSet rs = stmt.executeQuery( "SELECT * FROM COMPANY;" );
             while ( rs.next() ) {
                int id = rs.getInt("id");
                String  name = rs.getString("name");
                int age  = rs.getInt("age");
                String  address = rs.getString("address");
                float salary = rs.getFloat("salary");
                System.out.println( "ID = " + id );
                System.out.println( "NAME = " + name );
                System.out.println( "AGE = " + age );
                System.out.println( "ADDRESS = " + address );
                System.out.println( "SALARY = " + salary );
                System.out.println();
             }
             rs.close();
             stmt.close();
             c.close();
          } catch ( Exception e ) {
             System.err.println( e.getClass().getName()+": "+ e.getMessage() );
             System.exit(0);
          }
          System.out.println("Operation done successfully");
       }
    }
    

    When the program is compiled and executed, it will produce the following result −

    Opened database successfully
    ID = 1
    NAME = Paul
    AGE = 32
    ADDRESS = California
    SALARY = 20000.0
    
    ID = 2
    NAME = Allen
    AGE = 25
    ADDRESS = Texas
    SALARY = 15000.0
    
    ID = 3
    NAME = Teddy
    AGE = 23
    ADDRESS = Norway
    SALARY = 20000.0
    
    ID = 4
    NAME = Mark
    AGE = 25
    ADDRESS = Rich-Mond
    SALARY = 65000.0
    
    Operation done successfully
    

    UPDATE Operation

    The following Java code shows how we can use the UPDATE statement to update any record and then fetch and display updated records from our COMPANY table −

    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.Statement;
    
    
    public class PostgreSQLJDBC {
       public static void main( String args[] ) {
          Connection c = null;
          Statement stmt = null;
          try {
             Class.forName("org.postgresql.Driver");
             c = DriverManager
                .getConnection("jdbc:postgresql://localhost:5432/testdb",
                "manisha", "123");
             c.setAutoCommit(false);
             System.out.println("Opened database successfully");
    
             stmt = c.createStatement();
             String sql = "UPDATE COMPANY set SALARY = 25000.00 where ID=1;";
             stmt.executeUpdate(sql);
             c.commit();
    
             ResultSet rs = stmt.executeQuery( "SELECT * FROM COMPANY;" );
             while ( rs.next() ) {
                int id = rs.getInt("id");
                String  name = rs.getString("name");
                int age  = rs.getInt("age");
                String  address = rs.getString("address");
                float salary = rs.getFloat("salary");
                System.out.println( "ID = " + id );
                System.out.println( "NAME = " + name );
                System.out.println( "AGE = " + age );
                System.out.println( "ADDRESS = " + address );
                System.out.println( "SALARY = " + salary );
                System.out.println();
             }
             rs.close();
             stmt.close();
             c.close();
          } catch ( Exception e ) {
             System.err.println( e.getClass().getName()+": "+ e.getMessage() );
             System.exit(0);
          }
          System.out.println("Operation done successfully");
       }
    }
    

    When the program is compiled and executed, it will produce the following result −

    Opened database successfully
    ID = 2
    NAME = Allen
    AGE = 25
    ADDRESS = Texas
    SALARY = 15000.0
    
    ID = 3
    NAME = Teddy
    AGE = 23
    ADDRESS = Norway
    SALARY = 20000.0
    
    ID = 4
    NAME = Mark
    AGE = 25
    ADDRESS = Rich-Mond
    SALARY = 65000.0
    
    ID = 1
    NAME = Paul
    AGE = 32
    ADDRESS = California
    SALARY = 25000.0
    
    Operation done successfully
    

    DELETE Operation

    The following Java code shows how we can use the DELETE statement to delete any record and then fetch and display remaining records from our COMPANY table −

    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.Statement;
    
    
    public class PostgreSQLJDBC6 {
       public static void main( String args[] ) {
          Connection c = null;
          Statement stmt = null;
          try {
             Class.forName("org.postgresql.Driver");
             c = DriverManager
                .getConnection("jdbc:postgresql://localhost:5432/testdb",
                "manisha", "123");
             c.setAutoCommit(false);
             System.out.println("Opened database successfully");
    
             stmt = c.createStatement();
             String sql = "DELETE from COMPANY where ID = 2;";
             stmt.executeUpdate(sql);
             c.commit();
    
             ResultSet rs = stmt.executeQuery( "SELECT * FROM COMPANY;" );
             while ( rs.next() ) {
                int id = rs.getInt("id");
                String  name = rs.getString("name");
                int age  = rs.getInt("age");
                String  address = rs.getString("address");
                float salary = rs.getFloat("salary");
                System.out.println( "ID = " + id );
                System.out.println( "NAME = " + name );
                System.out.println( "AGE = " + age );
                System.out.println( "ADDRESS = " + address );
                System.out.println( "SALARY = " + salary );
                System.out.println();
             }
             rs.close();
             stmt.close();
             c.close();
          } catch ( Exception e ) {
             System.err.println( e.getClass().getName()+": "+ e.getMessage() );
             System.exit(0);
          }
          System.out.println("Operation done successfully");
       }
    }
    

    When the program is compiled and executed, it will produce the following result −

    Opened database successfully
    ID = 3
    NAME = Teddy
    AGE = 23
    ADDRESS = Norway
    SALARY = 20000.0
    
    ID = 4
    NAME = Mark
    AGE = 25
    ADDRESS = Rich-Mond
    SALARY = 65000.0
    
    ID = 1
    NAME = Paul
    AGE = 32
    ADDRESS = California
    SALARY = 25000.0
    Operation done successfully
    

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí PostgreSQL – PHP nhận dự án làm có lương

    PostgreSQL – PHP Interface



    Installation

    The PostgreSQL extension is enabled by default in the latest releases of PHP 5.3.x. It is possible to disable it by using –without-pgsql at compile time. Still you can use yum command to install PHP -PostgreSQL interface −

    yum install php-pgsql
    

    Before you start using the PHP PostgreSQL interface, find the pg_hba.conf file in your PostgreSQL installation directory and add the following line −

    # IPv4 local connections:
    host    all         all         127.0.0.1/32          md5
    

    You can start/restart the postgres server, in case it is not running, using the following command −

    [root@host]# service postgresql restart
    Stopping postgresql service:                               [  OK  ]
    Starting postgresql service:                               [  OK  ]
    

    Windows users must enable php_pgsql.dll in order to use this extension. This DLL is included with Windows distributions in the latest releases of PHP 5.3.x

    For detailed installation instructions, kindly check our PHP tutorial and its official website.

    PHP Interface APIs

    The following are important PHP routines, which can suffice your requirement to work with PostgreSQL database from your PHP program. If you are looking for a more sophisticated application, then you can look into the PHP official documentation.

    S. No. API & Description
    1

    resource pg_connect ( string $connection_string [, int $connect_type ] )

    This opens a connection to a PostgreSQL database specified by the connection_string.

    If PGSQL_CONNECT_FORCE_NEW is passed as connect_type, then a new connection is created in case of a second call to pg_connect(), even if the connection_string is identical to an existing connection.

    2

    bool pg_connection_reset ( resource $connection )

    This routine resets the connection. It is useful for error recovery. Returns TRUE on success or FALSE on failure.

    3

    int pg_connection_status ( resource $connection )

    This routine returns the status of the specified connection. Returns PGSQL_CONNECTION_OK or PGSQL_CONNECTION_BAD.

    4

    string pg_dbname ([ resource $connection ] )

    This routine returns the name of the database that the given PostgreSQL connection resource.

    5

    resource pg_prepare ([ resource $connection ], string $stmtname, string $query )

    This submits a request to create a prepared statement with the given parameters and waits for completion.

    6

    resource pg_execute ([ resource $connection ], string $stmtname, array $params )

    This routine sends a request to execute a prepared statement with given parameters and waits for the result.

    7

    resource pg_query ([ resource $connection ], string $query )

    This routine executes the query on the specified database connection.

    8

    array pg_fetch_row ( resource $result [, int $row ] )

    This routine fetches one row of data from the result associated with the specified result resource.

    9

    array pg_fetch_all ( resource $result )

    This routine returns an array that contains all rows (records) in the result resource.

    10

    int pg_affected_rows ( resource $result )

    This routine returns the number of rows affected by INSERT, UPDATE, and DELETE queries.

    11

    int pg_num_rows ( resource $result )

    This routine returns the number of rows in a PostgreSQL result resource for example number of rows returned by SELECT statement.

    12

    bool pg_close ([ resource $connection ] )

    This routine closes the non-persistent connection to a PostgreSQL database associated with the given connection resource.

    13

    string pg_last_error ([ resource $connection ] )

    This routine returns the last error message for a given connection.

    14

    string pg_escape_literal ([ resource $connection ], string $data )

    This routine escapes a literal for insertion into a text field.

    15

    string pg_escape_string ([ resource $connection ], string $data )

    This routine escapes a string for querying the database.

    Connecting to Database

    The following PHP code shows how to connect to an existing database on a local machine and finally a database connection object will be returned.

    <?php
       $host        = "host = 127.0.0.1";
       $port        = "port = 5432";
       $dbname      = "dbname = testdb";
       $credentials = "user = postgres password=pass123";
    
       $db = pg_connect( "$host $port $dbname $credentials"  );
       if(!$db) {
          echo "Error : Unable to open databasen";
       } else {
          echo "Opened database successfullyn";
       }
    ?>
    

    Now, let us run the above given program to open our database testdb: if the database is successfully opened, then it will give the following message −

    Opened database successfully
    

    Create a Table

    The following PHP program will be used to create a table in a previously created database −

    <?php
       $host        = "host = 127.0.0.1";
       $port        = "port = 5432";
       $dbname      = "dbname = testdb";
       $credentials = "user = postgres password=pass123";
    
       $db = pg_connect( "$host $port $dbname $credentials"  );
       if(!$db) {
          echo "Error : Unable to open databasen";
       } else {
          echo "Opened database successfullyn";
       }
    
       $sql =<<<EOF
          CREATE TABLE COMPANY
          (ID INT PRIMARY KEY     NOT NULL,
          NAME           TEXT    NOT NULL,
          AGE            INT     NOT NULL,
          ADDRESS        CHAR(50),
          SALARY         REAL);
    EOF;
    
       $ret = pg_query($db, $sql);
       if(!$ret) {
          echo pg_last_error($db);
       } else {
          echo "Table created successfullyn";
       }
       pg_close($db);
    ?>
    

    When the above given program is executed, it will create COMPANY table in your testdb and it will display the following messages −

    Opened database successfully
    Table created successfully
    

    INSERT Operation

    The following PHP program shows how we can create records in our COMPANY table created in above example −

    <?php
       $host        = "host=127.0.0.1";
       $port        = "port=5432";
       $dbname      = "dbname = testdb";
       $credentials = "user = postgres password=pass123";
    
       $db = pg_connect( "$host $port $dbname $credentials"  );
       if(!$db) {
          echo "Error : Unable to open databasen";
       } else {
          echo "Opened database successfullyn";
       }
    
       $sql =<<<EOF
          INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)
          VALUES (1, ''Paul'', 32, ''California'', 20000.00 );
    
          INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)
          VALUES (2, ''Allen'', 25, ''Texas'', 15000.00 );
    
          INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)
          VALUES (3, ''Teddy'', 23, ''Norway'', 20000.00 );
    
          INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)
          VALUES (4, ''Mark'', 25, ''Rich-Mond '', 65000.00 );
    EOF;
    
       $ret = pg_query($db, $sql);
       if(!$ret) {
          echo pg_last_error($db);
       } else {
          echo "Records created successfullyn";
       }
       pg_close($db);
    ?>
    

    When the above given program is executed, it will create the given records in COMPANY table and will display the following two lines −

    Opened database successfully
    Records created successfully
    

    SELECT Operation

    The following PHP program shows how we can fetch and display records from our COMPANY table created in above example −

    <?php
       $host        = "host = 127.0.0.1";
       $port        = "port = 5432";
       $dbname      = "dbname = testdb";
       $credentials = "user = postgres password=pass123";
    
       $db = pg_connect( "$host $port $dbname $credentials"  );
       if(!$db) {
          echo "Error : Unable to open databasen";
       } else {
          echo "Opened database successfullyn";
       }
    
       $sql =<<<EOF
          SELECT * from COMPANY;
    EOF;
    
       $ret = pg_query($db, $sql);
       if(!$ret) {
          echo pg_last_error($db);
          exit;
       }
       while($row = pg_fetch_row($ret)) {
          echo "ID = ". $row[0] . "n";
          echo "NAME = ". $row[1] ."n";
          echo "ADDRESS = ". $row[2] ."n";
          echo "SALARY =  ".$row[4] ."nn";
       }
       echo "Operation done successfullyn";
       pg_close($db);
    ?>
    

    When the above given program is executed, it will produce the following result. Keep a note that fields are returned in the sequence they were used while creating table.

    Opened database successfully
    ID = 1
    NAME = Paul
    ADDRESS = California
    SALARY =  20000
    
    ID = 2
    NAME = Allen
    ADDRESS = Texas
    SALARY =  15000
    
    ID = 3
    NAME = Teddy
    ADDRESS = Norway
    SALARY =  20000
    
    ID = 4
    NAME = Mark
    ADDRESS = Rich-Mond
    SALARY =  65000
    
    Operation done successfully
    

    UPDATE Operation

    The following PHP code shows how we can use the UPDATE statement to update any record and then fetch and display updated records from our COMPANY table −

    <?php
       $host        = "host=127.0.0.1";
       $port        = "port=5432";
       $dbname      = "dbname = testdb";
       $credentials = "user = postgres password=pass123";
    
       $db = pg_connect( "$host $port $dbname $credentials"  );
       if(!$db) {
          echo "Error : Unable to open databasen";
       } else {
          echo "Opened database successfullyn";
       }
       $sql =<<<EOF
          UPDATE COMPANY set SALARY = 25000.00 where ID=1;
    EOF;
       $ret = pg_query($db, $sql);
       if(!$ret) {
          echo pg_last_error($db);
          exit;
       } else {
          echo "Record updated successfullyn";
       }
    
       $sql =<<<EOF
          SELECT * from COMPANY;
    EOF;
    
       $ret = pg_query($db, $sql);
       if(!$ret) {
          echo pg_last_error($db);
          exit;
       }
       while($row = pg_fetch_row($ret)) {
          echo "ID = ". $row[0] . "n";
          echo "NAME = ". $row[1] ."n";
          echo "ADDRESS = ". $row[2] ."n";
          echo "SALARY =  ".$row[4] ."nn";
       }
       echo "Operation done successfullyn";
       pg_close($db);
    ?>
    

    When the above given program is executed, it will produce the following result −

    Opened database successfully
    Record updated successfully
    ID = 2
    NAME = Allen
    ADDRESS = 25
    SALARY =  15000
    
    ID = 3
    NAME = Teddy
    ADDRESS = 23
    SALARY =  20000
    
    ID = 4
    NAME = Mark
    ADDRESS = 25
    SALARY =  65000
    
    ID = 1
    NAME = Paul
    ADDRESS = 32
    SALARY =  25000
    
    Operation done successfully
    

    DELETE Operation

    The following PHP code shows how we can use the DELETE statement to delete any record and then fetch and display the remaining records from our COMPANY table −

    <?php
       $host        = "host = 127.0.0.1";
       $port        = "port = 5432";
       $dbname      = "dbname = testdb";
       $credentials = "user = postgres password=pass123";
    
       $db = pg_connect( "$host $port $dbname $credentials"  );
       if(!$db) {
          echo "Error : Unable to open databasen";
       } else {
          echo "Opened database successfullyn";
       }
       $sql =<<<EOF
          DELETE from COMPANY where ID=2;
    EOF;
       $ret = pg_query($db, $sql);
       if(!$ret) {
          echo pg_last_error($db);
          exit;
       } else {
          echo "Record deleted successfullyn";
       }
    
       $sql =<<<EOF
          SELECT * from COMPANY;
    EOF;
    
       $ret = pg_query($db, $sql);
       if(!$ret) {
          echo pg_last_error($db);
          exit;
       }
       while($row = pg_fetch_row($ret)) {
          echo "ID = ". $row[0] . "n";
          echo "NAME = ". $row[1] ."n";
          echo "ADDRESS = ". $row[2] ."n";
          echo "SALARY =  ".$row[4] ."nn";
       }
       echo "Operation done successfullyn";
       pg_close($db);
    ?>
    

    When the above given program is executed, it will produce the following result −

    Opened database successfully
    Record deleted successfully
    ID = 3
    NAME = Teddy
    ADDRESS = 23
    SALARY =  20000
    
    ID = 4
    NAME = Mark
    ADDRESS = 25
    SALARY =  65000
    
    ID = 1
    NAME = Paul
    ADDRESS = 32
    SALARY =  25000
    
    Operation done successfully
    

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí PostgreSQL – Triggers nhận dự án làm có lương

    PostgreSQL – TRIGGERS



    PostgreSQL Triggers are database callback functions, which are automatically performed/invoked when a specified database event occurs.

    The following are important points about PostgreSQL triggers −

    • PostgreSQL trigger can be specified to fire

      • Before the operation is attempted on a row (before constraints are checked and the INSERT, UPDATE or DELETE is attempted)

      • After the operation has completed (after constraints are checked and the INSERT, UPDATE, or DELETE has completed)

      • Instead of the operation (in the case of inserts, updates or deletes on a view)

    • A trigger that is marked FOR EACH ROW is called once for every row that the operation modifies. In contrast, a trigger that is marked FOR EACH STATEMENT only executes once for any given operation, regardless of how many rows it modifies.

    • Both, the WHEN clause and the trigger actions, may access elements of the row being inserted, deleted or updated using references of the form NEW.column-name and OLD.column-name, where column-name is the name of a column from the table that the trigger is associated with.

    • If a WHEN clause is supplied, the PostgreSQL statements specified are only executed for rows for which the WHEN clause is true. If no WHEN clause is supplied, the PostgreSQL statements are executed for all rows.

    • If multiple triggers of the same kind are defined for the same event, they will be fired in alphabetical order by name.

    • The BEFORE, AFTER or INSTEAD OF keyword determines when the trigger actions will be executed relative to the insertion, modification or removal of the associated row.

    • Triggers are automatically dropped when the table that they are associated with is dropped.

    • The table to be modified must exist in the same database as the table or view to which the trigger is attached and one must use just tablename, not database.tablename.

    • A CONSTRAINT option when specified creates a constraint trigger. This is the same as a regular trigger except that the timing of the trigger firing can be adjusted using SET CONSTRAINTS. Constraint triggers are expected to raise an exception when the constraints they implement are violated.

    Syntax

    The basic syntax of creating a trigger is as follows −

    CREATE  TRIGGER trigger_name [BEFORE|AFTER|INSTEAD OF] event_name
    ON table_name
    [
     -- Trigger logic goes here....
    ];
    

    Here, event_name could be INSERT, DELETE, UPDATE, and TRUNCATE database operation on the mentioned table table_name. You can optionally specify FOR EACH ROW after table name.

    The following is the syntax of creating a trigger on an UPDATE operation on one or more specified columns of a table as follows −

    CREATE  TRIGGER trigger_name [BEFORE|AFTER] UPDATE OF column_name
    ON table_name
    [
     -- Trigger logic goes here....
    ];
    

    Example

    Let us consider a case where we want to keep audit trial for every record being inserted in COMPANY table, which we will create newly as follows (Drop COMPANY table if you already have it).

    testdb=# CREATE TABLE COMPANY(
       ID INT PRIMARY KEY     NOT NULL,
       NAME           TEXT    NOT NULL,
       AGE            INT     NOT NULL,
       ADDRESS        CHAR(50),
       SALARY         REAL
    );
    

    To keep audit trial, we will create a new table called AUDIT where log messages will be inserted whenever there is an entry in COMPANY table for a new record −

    testdb=# CREATE TABLE AUDIT(
       EMP_ID INT NOT NULL,
       ENTRY_DATE TEXT NOT NULL
    );
    

    Here, ID is the AUDIT record ID, and EMP_ID is the ID, which will come from COMPANY table, and DATE will keep timestamp when the record will be created in COMPANY table. So now, let us create a trigger on COMPANY table as follows −

    testdb=# CREATE TRIGGER example_trigger AFTER INSERT ON COMPANY
    FOR EACH ROW EXECUTE PROCEDURE auditlogfunc();
    

    Where auditlogfunc() is a PostgreSQL procedure and has the following definition −

    CREATE OR REPLACE FUNCTION auditlogfunc() RETURNS TRIGGER AS $example_table$
       BEGIN
          INSERT INTO AUDIT(EMP_ID, ENTRY_DATE) VALUES (new.ID, current_timestamp);
          RETURN NEW;
       END;
    $example_table$ LANGUAGE plpgsql;
    

    Now, we will start the actual work. Let us start inserting record in COMPANY table which should result in creating an audit log record in AUDIT table. So let us create one record in COMPANY table as follows −

    testdb=# INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)
    VALUES (1, ''Paul'', 32, ''California'', 20000.00 );
    

    This will create one record in COMPANY table, which is as follows −

     id | name | age | address      | salary
    ----+------+-----+--------------+--------
      1 | Paul |  32 | California   |  20000

    Same time, one record will be created in AUDIT table. This record is the result of a trigger, which we have created on INSERT operation on COMPANY table. Similarly, you can create your triggers on UPDATE and DELETE operations based on your requirements.

     emp_id |          entry_date
    --------+-------------------------------
          1 | 2013-05-05 15:49:59.968+05:30
    (1 row)
    

    Listing TRIGGERS

    You can list down all the triggers in the current database from pg_trigger table as follows −

    testdb=# SELECT * FROM pg_trigger;
    

    The above given PostgreSQL statement will list down all triggers.

    If you want to list the triggers on a particular table, then use AND clause with table name as follows −

    testdb=# SELECT tgname FROM pg_trigger, pg_class WHERE tgrelid=pg_class.oid AND relname=''company
    

    The above given PostgreSQL statement will also list down only one entry as follows −

         tgname
    -----------------
     example_trigger
    (1 row)
    

    Dropping TRIGGERS

    The following is the DROP command, which can be used to drop an existing trigger −

    testdb=# DROP TRIGGER trigger_name;
    

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí PostgreSQL – Indexes nhận dự án làm có lương

    PostgreSQL – INDEXES



    Indexes are special lookup tables that the database search engine can use to speed up data retrieval. Simply put, an index is a pointer to data in a table. An index in a database is very similar to an index in the back of a book.

    For example, if you want to reference all pages in a book that discusses a certain topic, you have to first refer to the index, which lists all topics alphabetically and then refer to one or more specific page numbers.

    An index helps to speed up SELECT queries and WHERE clauses; however, it slows down data input, with UPDATE and INSERT statements. Indexes can be created or dropped with no effect on the data.

    Creating an index involves the CREATE INDEX statement, which allows you to name the index, to specify the table and which column or columns to index, and to indicate whether the index is in ascending or descending order.

    Indexes can also be unique, similar to the UNIQUE constraint, in that the index prevents duplicate entries in the column or combination of columns on which there”s an index.

    The CREATE INDEX Command

    The basic syntax of CREATE INDEX is as follows −

    CREATE INDEX index_name ON table_name;
    

    Index Types

    PostgreSQL provides several index types: B-tree, Hash, GiST, SP-GiST and GIN. Each Index type uses a different algorithm that is best suited to different types of queries. By default, the CREATE INDEX command creates B-tree indexes, which fit the most common situations.

    Single-Column Indexes

    A single-column index is one that is created based on only one table column. The basic syntax is as follows −

    CREATE INDEX index_name
    ON table_name (column_name);
    

    Multicolumn Indexes

    A multicolumn index is defined on more than one column of a table. The basic syntax is as follows −

    CREATE INDEX index_name
    ON table_name (column1_name, column2_name);
    

    Whether to create a single-column index or a multicolumn index, take into consideration the column(s) that you may use very frequently in a query”s WHERE clause as filter conditions.

    Should there be only one column used, a single-column index should be the choice. Should there be two or more columns that are frequently used in the WHERE clause as filters, the multicolumn index would be the best choice.

    Unique Indexes

    Unique indexes are used not only for performance, but also for data integrity. A unique index does not allow any duplicate values to be inserted into the table. The basic syntax is as follows −

    CREATE UNIQUE INDEX index_name
    on table_name (column_name);
    

    Partial Indexes

    A partial index is an index built over a subset of a table; the subset is defined by a conditional expression (called the predicate of the partial index). The index contains entries only for those table rows that satisfy the predicate. The basic syntax is as follows −

    CREATE INDEX index_name
    on table_name (conditional_expression);
    

    Implicit Indexes

    Implicit indexes are indexes that are automatically created by the database server when an object is created. Indexes are automatically created for primary key constraints and unique constraints.

    Example

    The following is an example where we will create an index on table for salary column −

    # CREATE INDEX salary_index ON COMPANY (salary);
    

    Now, let us list down all the indices available on COMPANY table using d company command.

    # d company
    

    This will produce the following result, where company_pkey is an implicit index, which got created when the table was created.

           Table "public.company"
     Column  |     Type      | Modifiers
    ---------+---------------+-----------
     id      | integer       | not null
     name    | text          | not null
     age     | integer       | not null
     address | character(50) |
     salary  | real          |
    Indexes:
        "company_pkey" PRIMARY KEY, btree (id)
        "salary_index" btree (salary)
    

    You can list down the entire indexes database wide using the di command −

    The DROP INDEX Command

    An index can be dropped using PostgreSQL DROP command. Care should be taken when dropping an index because performance may be slowed or improved.

    The basic syntax is as follows −

    DROP INDEX index_name;
    

    You can use following statement to delete previously created index −

    # DROP INDEX salary_index;
    

    When Should Indexes be Avoided?

    Although indexes are intended to enhance a database”s performance, there are times when they should be avoided. The following guidelines indicate when the use of an index should be reconsidered −

    • Indexes should not be used on small tables.

    • Tables that have frequent, large batch update or insert operations.

    • Indexes should not be used on columns that contain a high number of NULL values.

    • Columns that are frequently manipulated should not be indexed.


    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí PostgreSQL – Alter Table Command nhận dự án làm có lương

    PostgreSQL – ALTER TABLE Command



    The PostgreSQL ALTER TABLE command is used to add, delete or modify columns in an existing table.

    You would also use ALTER TABLE command to add and drop various constraints on an existing table.

    Syntax

    The basic syntax of ALTER TABLE to add a new column in an existing table is as follows −

    ALTER TABLE table_name ADD column_name datatype;
    

    The basic syntax of ALTER TABLE to DROP COLUMN in an existing table is as follows −

    ALTER TABLE table_name DROP COLUMN column_name;
    

    The basic syntax of ALTER TABLE to change the DATA TYPE of a column in a table is as follows −

    ALTER TABLE table_name ALTER COLUMN column_name TYPE datatype;
    

    The basic syntax of ALTER TABLE to add a NOT NULL constraint to a column in a table is as follows −

    ALTER TABLE table_name MODIFY column_name datatype NOT NULL;
    

    The basic syntax of ALTER TABLE to ADD UNIQUE CONSTRAINT to a table is as follows −

    ALTER TABLE table_name
    ADD CONSTRAINT MyUniqueConstraint UNIQUE(column1, column2...);
    

    The basic syntax of ALTER TABLE to ADD CHECK CONSTRAINT to a table is as follows −

    ALTER TABLE table_name
    ADD CONSTRAINT MyUniqueConstraint CHECK (CONDITION);
    

    The basic syntax of ALTER TABLE to ADD PRIMARY KEY constraint to a table is as follows −

    ALTER TABLE table_name
    ADD CONSTRAINT MyPrimaryKey PRIMARY KEY (column1, column2...);
    

    The basic syntax of ALTER TABLE to DROP CONSTRAINT from a table is as follows −

    ALTER TABLE table_name
    DROP CONSTRAINT MyUniqueConstraint;
    

    If you are using MySQL, the code is as follows −

    ALTER TABLE table_name
    DROP INDEX MyUniqueConstraint;
    

    The basic syntax of ALTER TABLE to DROP PRIMARY KEY constraint from a table is as follows −

    ALTER TABLE table_name
    DROP CONSTRAINT MyPrimaryKey;
    

    If you are using MySQL, the code is as follows −

    ALTER TABLE table_name
    DROP PRIMARY KEY;
    

    Example

    Consider our table has the following records −

     id | name  | age | address   | salary
    ----+-------+-----+-----------+--------
      1 | Paul  |  32 | California|  20000
      2 | Allen |  25 | Texas     |  15000
      3 | Teddy |  23 | Norway    |  20000
      4 | Mark  |  25 | Rich-Mond |  65000
      5 | David |  27 | Texas     |  85000
      6 | Kim   |  22 | South-Hall|  45000
      7 | James |  24 | Houston   |  10000
    

    The following is the example to ADD a new column in an existing table −

    testdb=# ALTER TABLE COMPANY ADD GENDER char(1);
    

    Now, COMPANY table is changed and the following would be the output from SELECT statement −

     id | name  | age | address     | salary | gender
    ----+-------+-----+-------------+--------+--------
      1 | Paul  |  32 | California  |  20000 |
      2 | Allen |  25 | Texas       |  15000 |
      3 | Teddy |  23 | Norway      |  20000 |
      4 | Mark  |  25 | Rich-Mond   |  65000 |
      5 | David |  27 | Texas       |  85000 |
      6 | Kim   |  22 | South-Hall  |  45000 |
      7 | James |  24 | Houston     |  10000 |
    (7 rows)
    

    The following is the example to DROP gender column from existing table −

    testdb=# ALTER TABLE COMPANY DROP GENDER;
    

    Now, COMPANY table is changed and the following would be the output from SELECT statement −

     id | name  | age | address   | salary
    ----+-------+-----+-----------+--------
      1 | Paul  |  32 | California|  20000
      2 | Allen |  25 | Texas     |  15000
      3 | Teddy |  23 | Norway    |  20000
      4 | Mark  |  25 | Rich-Mond |  65000
      5 | David |  27 | Texas     |  85000
      6 | Kim   |  22 | South-Hall|  45000
      7 | James |  24 | Houston   |  10000
    

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí Truncate Table Command nhận dự án làm có lương

    PostgreSQL – TRUNCATE TABLE Command



    The PostgreSQL TRUNCATE TABLE command is used to delete complete data from an existing table. You can also use DROP TABLE command to delete complete table but it would remove complete table structure from the database and you would need to re-create this table once again if you wish to store some data.

    It has the same effect as DELETE on each table, but since it does not actually scan the tables, it is faster. Furthermore, it reclaims disk space immediately, rather than requiring a subsequent VACUUM operation. This is most useful on large tables.

    Syntax

    The basic syntax of TRUNCATE TABLE is as follows −

    TRUNCATE TABLE  table_name;
    

    Example

    Consider the COMPANY table has the following records −

     id | name  | age | address    | salary
    ----+-------+-----+------------+--------
      1 | Paul  |  32 | California |  20000
      2 | Allen |  25 | Texas      |  15000
      3 | Teddy |  23 | Norway     |  20000
      4 | Mark  |  25 | Rich-Mond  |  65000
      5 | David |  27 | Texas      |  85000
      6 | Kim   |  22 | South-Hall |  45000
      7 | James |  24 | Houston    |  10000
    (7 rows)
    

    The following is the example to truncate −

    testdb=# TRUNCATE TABLE COMPANY;
    

    Now, COMPANY table is truncated and the following would be the output of SELECT statement −

    testdb=# SELECT * FROM CUSTOMERS;
     id | name | age | address | salary
    ----+------+-----+---------+--------
    (0 rows)
    

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc