Postgresql 简明教程

PostgreSQL - DELETE Query

PostgreSQL DELETE 查询用于从表中删除现有记录。您可以将 WHERE 子句与 DELETE 查询一起使用以删除已选择的行。否则,所有记录都将被删除。

The PostgreSQL DELETE Query is used to delete the existing records from a table. You can use WHERE clause with DELETE query to delete the selected rows. Otherwise, all the records would be deleted.

Syntax

带 WHERE 子句的 DELETE 查询的基本语法如下 −

The basic syntax of DELETE query with WHERE clause is as follows −

DELETE FROM table_name
WHERE [condition];

可以使用 AND 或 OR 运算符组合 N 个条件。

You can combine N number of conditions using AND or OR operators.

Example

考虑表 COMPANY ,具有如下记录 −

Consider the table COMPANY, 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)

下面是一个示例,此示例将删除 ID 为 7 的客户 −

The following is an example, which would DELETE a customer whose ID is 7 −

testdb=# DELETE FROM COMPANY WHERE ID = 2;

现在,COMPANY 表将包含以下记录 −

Now, COMPANY table will have the following records −

 id | name  | age | address     | salary
----+-------+-----+-------------+--------
  1 | Paul  |  32 | California  |  20000
  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
(6 rows)

如果您想从 COMPANY 表中删除所有记录,不需要在 DELETE 查询中使用 WHERE 子句,如下所示 −

If you want to DELETE all the records from COMPANY table, you do not need to use WHERE clause with DELETE queries, which would be as follows −

testdb=# DELETE FROM COMPANY;

现在,COMPANY 表没有任何记录,因为所有记录都被 DELETE 语句删除。

Now, COMPANY table does not have any record because all the records have been deleted by the DELETE statement.