Author: alien

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

    PostgreSQL – LOCKS



    Locks or Exclusive Locks or Write Locks prevent users from modifying a row or an entire table. Rows modified by UPDATE and DELETE are then exclusively locked automatically for the duration of the transaction. This prevents other users from changing the row until the transaction is either committed or rolled back.

    The only time when users must wait for other users is when they are trying to modify the same row. If they modify different rows, no waiting is necessary. SELECT queries never have to wait.

    The database performs locking automatically. In certain cases, however, locking must be controlled manually. Manual locking can be done by using the LOCK command. It allows specification of a transaction”s lock type and scope.

    Syntax for LOCK command

    The basic syntax for LOCK command is as follows −

    LOCK [ TABLE ]
    name
     IN
    lock_mode
    
    • name − The name (optionally schema-qualified) of an existing table to lock. If ONLY is specified before the table name, only that table is locked. If ONLY is not specified, the table and all its descendant tables (if any) are locked.

    • lock_mode − The lock mode specifies which locks this lock conflicts with. If no lock mode is specified, then ACCESS EXCLUSIVE, the most restrictive mode, is used. Possible values are: ACCESS SHARE, ROW SHARE, ROW EXCLUSIVE, SHARE UPDATE EXCLUSIVE, SHARE, SHARE ROW EXCLUSIVE, EXCLUSIVE, ACCESS EXCLUSIVE.

    Once obtained, the lock is held for the remainder of the current transaction. There is no UNLOCK TABLE command; locks are always released at the transaction end.

    DeadLocks

    Deadlocks can occur when two transactions are waiting for each other to finish their operations. While PostgreSQL can detect them and end them with a ROLLBACK, deadlocks can still be inconvenient. To prevent your applications from running into this problem, make sure to design them in such a way that they will lock objects in the same order.

    Advisory Locks

    PostgreSQL provides means for creating locks that have application-defined meanings. These are called advisory locks. As the system does not enforce their use, it is up to the application to use them correctly. Advisory locks can be useful for locking strategies that are an awkward fit for the MVCC model.

    For example, a common use of advisory locks is to emulate pessimistic locking strategies typical of the so-called “flat file” data management systems. While a flag stored in a table could be used for the same purpose, advisory locks are faster, avoid table bloat, and are automatically cleaned up by the server at the end of the session.

    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 example locks the COMPANY table within the testdb database in ACCESS EXCLUSIVE mode. The LOCK statement works only in a transaction mode −

    testdb=#BEGIN;
    LOCK TABLE company1 IN ACCESS EXCLUSIVE MODE;
    

    The above given PostgreSQL statement will produce the following result −

    LOCK TABLE
    

    The above message indicates that the table is locked until the transaction ends and to finish the transaction you will have to either rollback or commit the transaction.


    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 – Views nhận dự án làm có lương

    PostgreSQL – VIEWS



    Views are pseudo-tables. That is, they are not real tables; nevertheless appear as ordinary tables to SELECT. A view can represent a subset of a real table, selecting certain columns or certain rows from an ordinary table. A view can even represent joined tables. Because views are assigned separate permissions, you can use them to restrict table access so that the users see only specific rows or columns of a table.

    A view can contain all rows of a table or selected rows from one or more tables. A view can be created from one or many tables, which depends on the written PostgreSQL query to create a view.

    Views, which are kind of virtual tables, allow users to do the following −

    • Structure data in a way that users or classes of users find natural or intuitive.

    • Restrict access to the data such that a user can only see limited data instead of complete table.

    • Summarize data from various tables, which can be used to generate reports.

    Since views are not ordinary tables, you may not be able to execute a DELETE, INSERT, or UPDATE statement on a view. However, you can create a RULE to correct this problem of using DELETE, INSERT or UPDATE on a view.

    Creating Views

    The PostgreSQL views are created using the CREATE VIEW statement. The PostgreSQL views can be created from a single table, multiple tables, or another view.

    The basic CREATE VIEW syntax is as follows −

    CREATE [TEMP | TEMPORARY] VIEW view_name AS
    SELECT column1, column2.....
    FROM table_name
    WHERE [condition];
    

    You can include multiple tables in your SELECT statement in very similar way as you use them in normal PostgreSQL SELECT query. If the optional TEMP or TEMPORARY keyword is present, the view will be created in the temporary space. Temporary views are automatically dropped at the end of the current session.

    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, following is an example to create a view from COMPANY table. This view would be used to have only few columns from COMPANY table −

    testdb=# CREATE VIEW COMPANY_VIEW AS
    SELECT ID, NAME, AGE
    FROM  COMPANY;
    

    Now, you can query COMPANY_VIEW in a similar way as you query an actual table. Following is the example −

    testdb=# SELECT * FROM COMPANY_VIEW;
    

    This would produce the following result −

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

    Dropping Views

    To drop a view, simply use the DROP VIEW statement with the view_name. The basic DROP VIEW syntax is as follows −

    testdb=# DROP VIEW view_name;
    

    The following command will delete COMPANY_VIEW view, which we created in the last section −

    testdb=# DROP VIEW COMPANY_VIEW;
    

    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í 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 – 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í 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 – 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 – 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 – NULL Values nhận dự án làm có lương

    PostgreSQL – NULL Values



    The PostgreSQL NULL is the term used to represent a missing value. A NULL value in a table is a value in a field that appears to be blank.

    A field with a NULL value is a field with no value. It is very important to understand that a NULL value is different from a zero value or a field that contains spaces.

    Syntax

    The basic syntax of using NULL while creating a table is as follows −

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

    Here, NOT NULL signifies that column should always accept an explicit value of the given data type. There are two columns where we did not use NOT NULL. Hence, this means these columns could be NULL.>

    A field with a NULL value is one that has been left blank during record creation.

    Example

    The NULL value can cause problems when selecting data, because when comparing an unknown value to any other value, the result is always unknown and not included in the final results. Consider the following table, having the following records −

    ID          NAME        AGE         ADDRESS     SALARY
    ----------  ----------  ----------  ----------  ----------
    1           Paul        32          California  20000.0
    2           Allen       25          Texas       15000.0
    3           Teddy       23          Norway      20000.0
    4           Mark        25          Rich-Mond   65000.0
    5           David       27          Texas       85000.0
    6           Kim         22          South-Hall  45000.0
    7           James       24          Houston     10000.0
    

    Let us use the UPDATE statement to set few nullable values as NULL as follows −

    testdb=# UPDATE COMPANY SET ADDRESS = NULL, SALARY = NULL where ID IN(6,7);
    

    Now, COMPANY table should have 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 |             |
      7 | James |  24 |             |
    (7 rows)
    

    Next, let us see the usage of IS NOT NULL operator to list down all the records where SALARY is not NULL −

    testdb=#  SELECT  ID, NAME, AGE, ADDRESS, SALARY
       FROM COMPANY
       WHERE SALARY IS NOT NULL;
    

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

    The following is the usage of IS NULL operator which will list down all the records where SALARY is NULL −

    testdb=#  SELECT  ID, NAME, AGE, ADDRESS, SALARY
            FROM COMPANY
            WHERE SALARY IS NULL;
    

    The above given PostgreSQL statement will produce the following result −

     id | name  | age | address | salary
    ----+-------+-----+---------+--------
      6 | Kim   |  22 |         |
      7 | James |  24 |         |
    (2 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 – Unions Clause nhận dự án làm có lương

    PostgreSQL – UNIONS Clause



    The PostgreSQL UNION clause/operator is used to combine the results of two or more SELECT statements without returning any duplicate rows.

    To use UNION, each SELECT must have the same number of columns selected, the same number of column expressions, the same data type, and have them in the same order but they do not have to be the same length.

    Syntax

    The basic syntax of UNION is as follows −

    SELECT column1 [, column2 ]
    FROM table1 [, table2 ]
    [WHERE condition]
    
    UNION
    
    SELECT column1 [, column2 ]
    FROM table1 [, table2 ]
    [WHERE condition]
    

    Here, given condition could be any given expression based on your requirement.

    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 −

    testdb=# SELECT * from DEPARTMENT;
     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 let us join these two tables using SELECT statement along with UNION clause as follows −

    testdb=# SELECT EMP_ID, NAME, DEPT FROM COMPANY INNER JOIN DEPARTMENT
       ON COMPANY.ID = DEPARTMENT.EMP_ID
       UNION
          SELECT EMP_ID, NAME, DEPT FROM COMPANY LEFT OUTER JOIN DEPARTMENT
             ON COMPANY.ID = DEPARTMENT.EMP_ID;
    

    This would produce the following result −

     emp_id | name  |  dept
    --------+-------+--------------
          5 | David | Engineering
          6 | Kim   | Finance
          2 | Allen | Engineering
          3 | Teddy | Engineering
          4 | Mark  | Finance
          1 | Paul  | IT Billing
          7 | James | Finance
    (7 rows)
    

    The UNION ALL Clause

    The UNION ALL operator is used to combine the results of two SELECT statements including duplicate rows. The same rules that apply to UNION apply to the UNION ALL operator as well.

    Syntax

    The basic syntax of UNION ALL is as follows −

    SELECT column1 [, column2 ]
    FROM table1 [, table2 ]
    [WHERE condition]
    
    UNION ALL
    
    SELECT column1 [, column2 ]
    FROM table1 [, table2 ]
    [WHERE condition]
    

    Here, given condition could be any given expression based on your requirement.

    Example

    Now, let us join above-mentioned two tables in our SELECT statement as follows −

    testdb=# SELECT EMP_ID, NAME, DEPT FROM COMPANY INNER JOIN DEPARTMENT
       ON COMPANY.ID = DEPARTMENT.EMP_ID
       UNION ALL
          SELECT EMP_ID, NAME, DEPT FROM COMPANY LEFT OUTER JOIN DEPARTMENT
             ON COMPANY.ID = DEPARTMENT.EMP_ID;
    

    This would produce the following result −

     emp_id | name  | dept
    --------+-------+--------------
          1 | Paul  | IT Billing
          2 | Allen | Engineering
          7 | James | Finance
          3 | Teddy | Engineering
          4 | Mark  | Finance
          5 | David | Engineering
          6 | Kim   | Finance
          1 | Paul  | IT Billing
          2 | Allen | Engineering
          7 | James | Finance
          3 | Teddy | Engineering
          4 | Mark  | Finance
          5 | David | Engineering
          6 | Kim   | Finance
    (14 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