DELETE语句

DELETE语句可以从指定的表里删除满足WHERE子句的行。如果WHERE子句不存在,将删除表中所有行,结果只保留表结构。

语法格式

  1. DELETE FROM table_name
  2. [WHERE condition];

参数说明

  • table_name

    目标表的名称(可以有模式修饰)。

    取值范围:已存在的表名。

  • condition

    一个返回Boolean值的表达式,用于判断哪些行需要被删除。

示例

创建表customer_t1_bak,表的结构、数据与customer_t1一致。

  1. openGauss=# CREATE TABLE customer_t1_bak AS TABLE customer_t1;
  2. INSERT 0 9

创建的表customer_t1_bak,数据如下:

  1. openGauss=# SELECT * FROM customer_t1_bak;
  2. c_customer_sk | c_customer_id | c_first_name | c_last_name | amount
  3. ---------------+---------------+--------------+-------------+--------
  4. 3869 | hello | Grace | | 1000
  5. 3869 | hello | Grace | | 1000
  6. 3869 | | Grace | |
  7. 3869 | hello | | |
  8. 3869 | hello | | |
  9. | | | |
  10. 6985 | maps | Joes | | 2200
  11. 9976 | world | James | | 5000
  12. 4421 | Admin | Local | | 3000
  13. (9 rows)

执行如下语句删除customer_t1_bak中c_customer_sk等于3869的职员。

  1. openGauss=# DELETE FROM customer_t1_bak WHERE c_customer_sk = 3869;
  2. DELETE 5

得到的结果如下,可以看到c_customer_sk = 3869的行已经被删除。

  1. openGauss=# SELECT * FROM customer_t1_bak;
  2. c_customer_sk | c_customer_id | c_first_name | c_last_name | amount
  3. ---------------+---------------+--------------+-------------+--------
  4. | | | |
  5. 6985 | maps | Joes | | 2200
  6. 9976 | world | James | | 5000
  7. 4421 | Admin | Local | | 3000
  8. (4 rows)

不指定WHERE语句时,默认删除整张表的数据,仅保留表结构。

  1. openGauss=# DELETE FROM customer_t1_bak;
  2. DELETE 4

得到结果如下。

  1. openGauss=# SELECT * FROM customer_t1_bak;
  2. c_customer_sk | c_customer_id | c_first_name | c_last_name | amount
  3. ---------------+---------------+--------------+-------------+--------
  4. (0 rows)