Category: postgresql

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

    PostgreSQL – ALIAS Syntax



    You can rename a table or a column temporarily by giving another name, which is known as ALIAS. The use of table aliases means to rename a table in a particular PostgreSQL statement. Renaming is a temporary change and the actual table name does not change in the database.

    The column aliases are used to rename a table”s columns for the purpose of a particular PostgreSQL query.

    Syntax

    The basic syntax of table alias is as follows −

    SELECT column1, column2....
    FROM table_name AS alias_name
    WHERE [condition];
    

    The basic syntax of column alias is as follows −

    SELECT column_name AS alias_name
    FROM table_name
    WHERE [condition];
    

    Example

    Consider the following two tables, (a) table is as follows −

    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)
    

    (b) Another table is as follows −

     id | dept         | emp_id
    ----+--------------+--------
      1 | IT Billing   |      1
      2 | Engineering  |      2
      3 | Finance      |      7
      4 | Engineering  |      3
      5 | Finance      |      4
      6 | Engineering  |      5
      7 | Finance      |      6
    (7 rows)
    

    Now, following is the usage of TABLE ALIAS where we use C and D as aliases for COMPANY and DEPARTMENT tables, respectively −

    testdb=# SELECT C.ID, C.NAME, C.AGE, D.DEPT
       FROM COMPANY AS C, DEPARTMENT AS D
       WHERE  C.ID = D.EMP_ID;
    

    The above given PostgreSQL statement will produce the following result −

     id | name  | age |  dept
    ----+-------+-----+------------
      1 | Paul  |  32 | IT Billing
      2 | Allen |  25 | Engineering
      7 | James |  24 | Finance
      3 | Teddy |  23 | Engineering
      4 | Mark  |  25 | Finance
      5 | David |  27 | Engineering
      6 | Kim   |  22 | Finance
    (7 rows)
    

    Let us see an example for the usage of COLUMN ALIAS where COMPANY_ID is an alias of ID column and COMPANY_NAME is an alias of name column −

    testdb=# SELECT C.ID AS COMPANY_ID, C.NAME AS COMPANY_NAME, C.AGE, D.DEPT
       FROM COMPANY AS C, DEPARTMENT AS D
       WHERE  C.ID = D.EMP_ID;
    

    The above given PostgreSQL statement will produce the following result −

     company_id | company_name | age | dept
    ------------+--------------+-----+------------
          1     | Paul         |  32 | IT Billing
          2     | Allen        |  25 | Engineering
          7     | James        |  24 | Finance
          3     | Teddy        |  23 | Engineering
          4     | Mark         |  25 | Finance
          5     | David        |  27 | Engineering
          6     | Kim          |  22 | Finance
    (7 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

  • 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

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

    PostgreSQL – TRANSACTIONS



    A transaction is a unit of work that is performed against a database. Transactions are units or sequences of work accomplished in a logical order, whether in a manual fashion by a user or automatically by some sort of a database program.

    A transaction is the propagation of one or more changes to the database. For example, if you are creating a record, updating a record, or deleting a record from the table, then you are performing transaction on the table. It is important to control transactions to ensure data integrity and to handle database errors.

    Practically, you will club many PostgreSQL queries into a group and you will execute all of them together as a part of a transaction.

    Properties of Transactions

    Transactions have the following four standard properties, usually referred to by the acronym ACID −

    • Atomicity − Ensures that all operations within the work unit are completed successfully; otherwise, the transaction is aborted at the point of failure and previous operations are rolled back to their former state.

    • Consistency − Ensures that the database properly changes states upon a successfully committed transaction.

    • Isolation − Enables transactions to operate independently of and transparent to each other.

    • Durability − Ensures that the result or effect of a committed transaction persists in case of a system failure.

    Transaction Control

    The following commands are used to control transactions −

    • BEGIN TRANSACTION − To start a transaction.

    • COMMIT − To save the changes, alternatively you can use END TRANSACTION command.

    • ROLLBACK − To rollback the changes.

    Transactional control commands are only used with the DML commands INSERT, UPDATE and DELETE only. They cannot be used while creating tables or dropping them because these operations are automatically committed in the database.

    The BEGIN TRANSACTION Command

    Transactions can be started using BEGIN TRANSACTION or simply BEGIN command. Such transactions usually persist until the next COMMIT or ROLLBACK command is encountered. But a transaction will also ROLLBACK if the database is closed or if an error occurs.

    The following is the simple syntax to start a transaction −

    BEGIN;
    
    or
    
    BEGIN TRANSACTION;
    

    The COMMIT Command

    The COMMIT command is the transactional command used to save changes invoked by a transaction to the database.

    The COMMIT command saves all transactions to the database since the last COMMIT or ROLLBACK command.

    The syntax for COMMIT command is as follows −

    COMMIT;
    
    or
    
    END TRANSACTION;
    

    The ROLLBACK Command

    The ROLLBACK command is the transactional command used to undo transactions that have not already been saved to the database.

    The ROLLBACK command can only be used to undo transactions since the last COMMIT or ROLLBACK command was issued.

    The syntax for ROLLBACK command is as follows −

    ROLLBACK;
    

    Example

    Consider the table is having 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
    

    Now, let us start a transaction and delete records from the table having age = 25 and finally we use ROLLBACK command to undo all the changes.

    testdb=# BEGIN;
    DELETE FROM COMPANY WHERE AGE = 25;
    ROLLBACK;
    

    If you will check COMPANY table is still having 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
    

    Now, let us start another transaction and delete records from the table having age = 25 and finally we use COMMIT command to commit all the changes.

    testdb=# BEGIN;
    DELETE FROM COMPANY WHERE AGE = 25;
    COMMIT;
    

    If you will check the COMPANY table, it still has the following records −

     id | name  | age | address    | salary
    ----+-------+-----+------------+--------
      1 | Paul  |  32 | California |  20000
      3 | Teddy |  23 | Norway     |  20000
      5 | David |  27 | Texas      |  85000
      6 | Kim   |  22 | South-Hall |  45000
      7 | James |  24 | Houston    |  10000
    (5 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

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

    PostgreSQL – LIMIT Clause



    The PostgreSQL LIMIT clause is used to limit the data amount returned by the SELECT statement.

    Syntax

    The basic syntax of SELECT statement with LIMIT clause is as follows −

    SELECT column1, column2, columnN
    FROM table_name
    LIMIT [no of rows]
    

    The following is the syntax of LIMIT clause when it is used along with OFFSET clause −

    SELECT column1, column2, columnN
    FROM table_name
    LIMIT [no of rows] OFFSET [row num]
    

    LIMIT and OFFSET allow you to retrieve just a portion of the rows that are generated by the rest of the query.

    Example

    Consider the table having records as follows −

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

    The following is an example, which limits the row in the table according to the number of rows you want to fetch from table −

    testdb=# SELECT * FROM COMPANY LIMIT 4;
    

    This would produce the following result −

     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
    (4 rows)
    

    However, in certain situation, you may need to pick up a set of records from a particular offset. Here is an example, which picks up three records starting from the third position −

    testdb=# SELECT * FROM COMPANY LIMIT 3 OFFSET 2;
    

    This would produce the following result −

     id | name  | age | address   | salary
    ----+-------+-----+-----------+--------
      3 | Teddy |  23 | Norway    |  20000
      4 | Mark  |  25 | Rich-Mond |  65000
      5 | David |  27 | Texas     |  85000
    (3 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

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

    PostgreSQL – ORDER BY Clause



    The PostgreSQL ORDER BY clause is used to sort the data in ascending or descending order, based on one or more columns.

    Syntax

    The basic syntax of ORDER BY clause is as follows −

    SELECT column-list
    FROM table_name
    [WHERE condition]
    [ORDER BY column1, column2, .. columnN] [ASC | DESC];
    

    You can use more than one column in the ORDER BY clause. Make sure whatever column you are using to sort, that column should be available in column-list.

    Example

    Consider the table having records as follows −

    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)
    

    The following is an example, which would sort the result in ascending order by SALARY −

    testdb=# SELECT * FROM COMPANY ORDER BY AGE ASC;
    

    This would produce the following result −

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

    The following is an example, which would sort the result in ascending order by NAME and SALARY −

    testdb=# SELECT * FROM COMPANY ORDER BY NAME, SALARY ASC;
    

    This would produce the following result −

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

    The following is an example, which would sort the result in descending order by NAME −

    testdb=# SELECT * FROM COMPANY ORDER BY NAME DESC;
    

    This would produce the following result −

     id | name  | age | address    | salary
    ----+-------+-----+------------+--------
      3 | Teddy |  23 | Norway     |  20000
      1 | Paul  |  32 | California |  20000
      8 | Paul  |  24 | Houston    |  20000
      4 | Mark  |  25 | Rich-Mond  |  65000
      6 | Kim   |  22 | South-Hall |  45000
      7 | James |  24 | Houston    |  10000
      9 | James |  44 | Norway     |   5000
     10 | James |  45 | Texas      |   5000
      5 | David |  27 | Texas      |  85000
      2 | Allen |  25 | Texas      |  15000
    (10 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

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

    PostgreSQL – WITH Clause



    In PostgreSQL, the WITH query provides a way to write auxiliary statements for use in a larger query. It helps in breaking down complicated and large queries into simpler forms, which are easily readable. These statements often referred to as Common Table Expressions or CTEs, can be thought of as defining temporary tables that exist just for one query.

    The WITH query being CTE query, is particularly useful when subquery is executed multiple times. It is equally helpful in place of temporary tables. It computes the aggregation once and allows us to reference it by its name (may be multiple times) in the queries.

    The WITH clause must be defined before it is used in the query.

    Syntax

    The basic syntax of WITH query is as follows −

    WITH
       name_for_summary_data AS (
          SELECT Statement)
       SELECT columns
       FROM name_for_summary_data
       WHERE conditions <=> (
          SELECT column
          FROM name_for_summary_data)
       [ORDER BY columns]
    

    Where name_for_summary_data is the name given to the WITH clause. The name_for_summary_data can be the same as an existing table name and will take precedence.

    You can use data-modifying statements (INSERT, UPDATE or DELETE) in WITH. This allows you to perform several different operations in the same query.

    Recursive WITH

    Recursive WITH or Hierarchical queries, is a form of CTE where a CTE can reference to itself, i.e., a WITH query can refer to its own output, hence the name recursive.

    Example

    Consider the table having records as follows −

    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)
    

    Now, let us write a query using the WITH clause to select the records from the above table, as follows −

    With CTE AS
    (Select
     ID
    , NAME
    , AGE
    , ADDRESS
    , SALARY
    FROM COMPANY )
    Select * From CTE;
    

    The above given PostgreSQL statement will produce the following result −

    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)
    

    Now, let us write a query using the RECURSIVE keyword along with the WITH clause, to find the sum of the salaries less than 20000, as follows −

    WITH RECURSIVE t(n) AS (
       VALUES (0)
       UNION ALL
       SELECT SALARY FROM COMPANY WHERE SALARY < 20000
    )
    SELECT sum(n) FROM t;
    

    The above given PostgreSQL statement will produce the following result −

      sum
    -------
     25000
    (1 row)
    

    Let us write a query using data modifying statements along with the WITH clause, as shown below.

    First, create a table COMPANY1 similar to the table COMPANY. The query in the example effectively moves rows from COMPANY to COMPANY1. The DELETE in WITH deletes the specified rows from COMPANY, returning their contents by means of its RETURNING clause; and then the primary query reads that output and inserts it into COMPANY1 TABLE −

    CREATE TABLE COMPANY1(
       ID INT PRIMARY KEY     NOT NULL,
       NAME           TEXT    NOT NULL,
       AGE            INT     NOT NULL,
       ADDRESS        CHAR(50),
       SALARY         REAL
    );
    
    WITH moved_rows AS (
       DELETE FROM COMPANY
       WHERE
          SALARY >= 30000
       RETURNING *
    )
    INSERT INTO COMPANY1 (SELECT * FROM moved_rows);
    

    The above given PostgreSQL statement will produce the following result −

    INSERT 0 3
    

    Now, the records in the tables COMPANY and COMPANY1 are as follows −

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

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

    PostgreSQL – DISTINCT Keyword



    The PostgreSQL DISTINCT keyword is used in conjunction with SELECT statement to eliminate all the duplicate records and fetching only unique records.

    There may be a situation when you have multiple duplicate records in a table. While fetching such records, it makes more sense to fetch only unique records instead of fetching duplicate records.

    Syntax

    The basic syntax of DISTINCT keyword to eliminate duplicate records is as follows −

    SELECT DISTINCT column1, column2,.....columnN
    FROM table_name
    WHERE [condition]
    

    Example

    Consider the table having records as follows −

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

    Let us add two more records to this table as follows −

    INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)
    VALUES (8, ''Paul'', 32, ''California'', 20000.00 );
    
    INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)
    VALUES (9, ''Allen'', 25, ''Texas'', 15000.00 );
    

    Now, the records in the COMPANY table would be −

     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
      8 | Paul  |  32 | California |  20000
      9 | Allen |  25 | Texas      |  15000
    (9 rows)
    

    First, let us see how the following SELECT query returns duplicate salary records −

    testdb=# SELECT name FROM COMPANY;
    

    This would produce the following result −

     name
    -------
     Paul
     Allen
     Teddy
     Mark
     David
     Kim
     James
     Paul
     Allen
    (9 rows)
    

    Now, let us use DISTINCT keyword with the above SELECT query and see the result −

    testdb=# SELECT DISTINCT name FROM COMPANY;
    

    This would produce the following result where we do not have any duplicate entry −

     name
    -------
     Teddy
     Paul
     Mark
     David
     Allen
     Kim
     James
    (7 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