PgSQL - Study Notes 14: Alias & Triggers & Indexes

Table of contents

PostgreSQL alias: rename a table or field name

PostgreSQL trigger: database callback function

Create trigger:

List triggers:

Delete trigger:

PostgreSQL index: a special table query that speeds up search engines' retrieval of data

CREATE INDEX statement: Create an index

Index type

Single column index: an index created based on only one column of the table

Composite index: an index created on multiple columns of the table

Unique index: does not allow any duplicate values ​​to be inserted into the table

Local index: is an index built on a subset of the table

Implicit index: an index automatically created by the database server when creating an object

List all indexes in a table: /d table_name

List all indexes in the database: /di

Delete index: DROP INDEX index_name;


PostgreSQL alias: rename a table or field name

We can use SQL to rename the name of a table or a field, and this name is called the alias of the table or field.

Aliases are created to make table or column names more readable.

AS is used in SQL   to create aliases.

/*表的别名语法:*/
SELECT column1, column2....
FROM table_name AS alias_name
WHERE [condition];

/*列的别名语法:*/
SELECT column_name AS alias_name
FROM table_name
WHERE [condition];

 Example:

mydb=# select * from company;
 id | name  | age |                      address                       | salary | join_date
----+-------+-----+----------------------------------------------------+--------+-----------
  1 | Paul  |  32 | California                                         |  20000 |
  2 | Allen |  25 | Texas                                              |  15000 |
  3 | Teddy |  23 | Norway                                             |  20000 |
  4 | Mark  |  25 | Rich-Mond                                          |  65000 |
  5 | David |  27 | South-Hall                                         |  85000 |
  8 | Paul  |  24 | Houston                                            |  20000 |
  9 | James |  44 | Norway                                             |   5000 |
 10 | James |  45 | Texas                                              |   5000 |
  6 | Kim   |  22 |                                                    |        |
  7 | James |  24 |                                                    |        |
(10 行记录)


mydb=# 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 行记录)

/*下面我们分别用 C 和 D 表示 COMPANY 表和 DEPAERMENT 表的别名:*/
mydb=# SELECT C.ID, C.NAME, C.AGE, D.DEPT FROM COMPANY AS C, DEPARTMENT AS D WHERE  C.ID = D.EMP_ID;
 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 行记录)

/*下面,我们用 COMPANY_ID 表示 ID 列,COMPANY_NAME 表示 NAME 列,来展示列别名的用法:*/
mydb=# 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;
 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 行记录)

PostgreSQL trigger: database callback function

A PostgreSQL trigger is a database callback function that is automatically executed/called when a specified database event occurs.

The following are some important points about PostgreSQL triggers:

  • PostgreSQL triggers can be triggered in the following situations:

    • Before performing an operation (before checking constraints and attempting to insert, update, or delete).
    • After the operation is performed (after the constraints have been checked and the insert, update, or delete has completed).
    • Update operations (when inserting, updating, or deleting a view).
  • The FOR EACH ROW attribute of the trigger is optional. If selected, it will be called once per row when the operation is modified;

  • In contrast, with FOR EACH STATEMENT selected , the trigger marked by each statement is executed once, regardless of how many rows are modified.

  • WHEN clauses and trigger actions can access each row element when inserting, deleting, or updating the form that references NEW.column-name and OLD.column-name. where column-name is the name of the column in the table associated with the trigger.

    • If a WHEN clause exists, the PostgreSQL statement will only execute the row for which the WHEN clause is true;

    • Without the WHEN clause, the PostgreSQL statement is executed on each row.

  • The BEFORE or AFTER keyword determines when the trigger action is executed, whether before or after the insertion, modification, or deletion of the associated row.

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

  • Constraint options are specified when creating a constraint trigger. This is the same as a regular trigger, except that you can use this constraint to adjust when the trigger fires. A constraint trigger throws an exception when a constraint implemented by a constraint trigger is violated.

Create trigger:

/*创建触发器时的基础语法如下:*/
CREATE  TRIGGER trigger_name [BEFORE|AFTER|INSTEAD OF] event_name
ON table_name
[
 -- 触发器逻辑....
];

/*event_name 可以是在所提到的表 table_name 上的 INSERT、DELETE 和 UPDATE 数据库操作。*/
/*您可以在表名后选择指定 FOR EACH ROW。*/

/*以下是在 UPDATE 操作上在表的一个或多个指定列上创建触发器的语法:*/
CREATE  TRIGGER trigger_name [BEFORE|AFTER] UPDATE OF column_name
ON table_name
[
 -- 触发器逻辑....
];

List triggers:

/*你可以把从 pg_trigger 表中把当前数据库所有触发器列举出来:*/
runoobdb=# SELECT * FROM pg_trigger;

/*列举出特定表的触发器,语法如下:*/
runoobdb=# SELECT tgname FROM pg_trigger, pg_class WHERE tgrelid=pg_class.oid AND relname='company';

Delete trigger:

/*基础语法如下:*
drop trigger ${trigger_name} on ${table_of_trigger_dependent};

/*删除本文上表 company 上的触发器 example_trigger 的指令为:*/
drop trigger example_trigger on company;

Example: 

postgres=# \c learn

/*让我们假设一个情况,我们要为被插入到新创建的 COMPANY 表中的每一个记录保持审计试验:*/
learn=# CREATE TABLE COMPANY(
learn(#    ID INT PRIMARY KEY     NOT NULL,
learn(#    NAME           TEXT    NOT NULL,
learn(#    AGE            INT     NOT NULL,
learn(#    ADDRESS        CHAR(50),
learn(#    SALARY         REAL
learn(# );
CREATE TABLE

/*为了保持审计试验,我们将创建一个名为 AUDIT 的新表。每当 COMPANY 表中有一个新的记录项时,日志消息将被插入其中:*/
//EMP_ID 是来自 COMPANY 表的 ID,DATE 将保持 COMPANY 中记录被创建时的时间戳。
learn=# CREATE TABLE AUDIT(
learn(#    EMP_ID INT NOT NULL,
learn(#    ENTRY_DATE TEXT NOT NULL
learn(# );
CREATE TABLE

/*在 COMPANY 表上创建一个触发器,如下所示:*/
learn=# CREATE TRIGGER example_trigger AFTER INSERT ON COMPANY FOR EACH ROW EXECUTE PROCEDURE auditlogfunc();
错误:  函数 auditlogfunc() 不存在

/*auditlogfunc() 是 PostgreSQL 一个程序,其定义如下:*/
learn=# CREATE OR REPLACE FUNCTION auditlogfunc() RETURNS TRIGGER AS $example_table$
learn$#    BEGIN
learn$#       INSERT INTO AUDIT(EMP_ID, ENTRY_DATE) VALUES (new.ID, current_timestamp);
learn$#       RETURN NEW;
learn$#    END;
learn$# $example_table$ LANGUAGE plpgsql;
CREATE FUNCTION

/*在 COMPANY 表上创建一个触发器,如下所示:*/
learn=# CREATE TRIGGER example_trigger AFTER INSERT ON COMPANY FOR EACH ROW EXECUTE PROCEDURE auditlogfunc();
CREATE TRIGGER

/*往 COMPANY 表中插入数据:*/
learn=# INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) VALUES (1, 'Paul', 32, 'California', 20000.00 );
INSERT 0 1

learn=# select * from company;
 id | name | age |                      address                       | salary
----+------+-----+----------------------------------------------------+--------
  1 | Paul |  32 | California                                         |  20000
(1 行记录)
/*这时,COMPANY 表中插入了一条记录:*/
/*同时, AUDIT 表中也插入了一条记录,因为我们在插入 COMPANY 表时创建了一个触发器。*/
learn=# select * from audit;
 emp_id |          entry_date
--------+-------------------------------
      1 | 2022-05-19 14:58:52.062211+08
(1 行记录)

/*从 pg_trigger 表中把当前数据库所有触发器列举出来:*/
learn=# select * from pg_trigger;
 tgrelid |     tgname      | tgfoid | tgtype | tgenabled | tgisinternal | tgconstrrelid | tgconstrindid | tgconstraint | tgdeferrable | tginitdeferred | tgnargs | tgattr | tgargs | tgqual | tgoldtable | tgnewtable
---------+-----------------+--------+--------+-----------+--------------+---------------+---------------+--------------+--------------+----------------+---------+--------+--------+--------+------------+------------
   17156 | example_trigger |  17170 |      5 | O         | f            |             0 |             0 |            0 | f            | f              |       0 |        | \x     |        |            |
(1 行记录)

/*列举出特定表的触发器,语法如下:*/
learn=# SELECT tgname FROM pg_trigger, pg_class WHERE tgrelid=pg_class.oid AND relname='company';
     tgname
-----------------
 example_trigger
(1 行记录)

/*删除上表 company 上的触发器 example_trigger 的指令为:*/
learn=# drop trigger example_trigger on company;
DROP TRIGGER
learn=# SELECT tgname FROM pg_trigger, pg_class WHERE tgrelid=pg_class.oid AND relname='company';
 tgname
--------
(0 行记录)

PostgreSQL index: a special table query that speeds up search engines' retrieval of data

An index is a special table query that speeds up search engines' retrieval of data.

Simply put, an index is a pointer to the data in the table.

An index in a database is very similar to an index in a book.

Take the table of contents page (index) of a Chinese dictionary as an example. We can quickly find the words we need through the table of contents (index) sorted by pinyin, strokes, radicals, etc.

  • Indexes help speed up SELECT queries and WHERE clauses, but they slow down data input when using UPDATE and INSERT statements. Indexes can be created or deleted without affecting the data.
  • Indexes are created using the CREATE INDEX statement, which allows you to name the index, specify the table and one or more columns to be indexed, and indicate whether the index is in ascending or descending order.

Indexes can also be unique, similar to UNIQUE constraints, preventing duplicate entries on a column or combination of columns.

CREATE INDEX statement: Create an index

/*CREATE INDEX (创建索引)的语法如下:*/
CREATE INDEX index_name ON table_name;

Index type

Single column index: an index created based on only one column of the table

/*基本语法如下:*/
CREATE INDEX index_name
ON table_name (column_name);

Composite index: an index created on multiple columns of the table

/*基本语法如下:*/
CREATE INDEX index_name
ON table_name (column1_name, column2_name...);

Whether it is a single column index or a composite index, the index must be a column that is used very frequently in the filter conditions of the WHERE clause.

If only one column is used, select a single column index; if there are multiple columns, use a combined index.

Unique index: does not allow any duplicate values ​​to be inserted into the table

Using unique indexes is not only for performance, but also for data integrity.

/*基本语法如下:*/
CREATE UNIQUE INDEX index_name
on table_name (column_name);

Local index: is an index built on a subset of the table

Subsets are defined by a conditional expression. The index only contains rows that meet the condition.

/*基本语法如下:*/
CREATE INDEX index_name
on table_name (conditional_expression);

Implicit index: an index automatically created by the database server when creating an object

Indexes are automatically created with primary key constraints and unique constraints.

List all indexes in a table: /d table_name

List all indexes in the database: /di

Delete index: DROP INDEX index_name;

Example:

/*在 COMPANY 表的 SALARY 列上创建索引:*/
learn=# CREATE INDEX salary_index ON COMPANY (salary);
CREATE INDEX

/*用 \d company 命令列出 COMPANY 表的所有索引:*/
learn=# \d company
                 数据表 "public.company"
  栏位   |     类型      | Collation | Nullable | Default
---------+---------------+-----------+----------+---------
 id      | integer       |           | not null |
 name    | text          |           | not null |
 age     | integer       |           | not null |
 address | character(50) |           |          |
 salary  | real          |           |          |
索引:
    "company_pkey" PRIMARY KEY, btree (id) /*company_pkey 是隐式索引 ,是表创建表时创建的:*/
    "salary_index" btree (salary)

/*用 \di 命令列出数据库中所有索引:*/
learn=# \di
                      关联列表
 架构模式 |     名称     | 类型 |  拥有者  | 数据表
----------+--------------+------+----------+---------
 public   | company_pkey | 索引 | postgres | company
 public   | salary_index | 索引 | postgres | company
(2 行记录)

/*DROP INDEX (删除索引)————删除之前创建的索引:*/
learn=# DROP INDEX salary_index;
DROP INDEX

learn=# \di
                      关联列表
 架构模式 |     名称     | 类型 |  拥有者  | 数据表
----------+--------------+------+----------+---------
 public   | company_pkey | 索引 | postgres | company
(1 行记录)

When should you avoid using indexes?

Although the purpose of indexes is to improve database performance, there are several situations where indexes should be avoided.

When using indexes, consider the following guidelines:

  • Indexes should not be used on smaller tables .
  • Indexes should not be used on tables that undergo frequent large-volume update or insert operations.
  • Indexes should not be used on columns that contain a large number of NULL values .
  • Indexes should not be used on frequently operated columns .

Guess you like

Origin blog.csdn.net/qq_41361442/article/details/124862735