Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

PostgreSQL TRUNCATE TABLE

PostgreSQL TRUNCATE TABLE

In PostgreSQL, TRUNCATE TABLE is used to delete the data in a table but not the table structure.

You can also use DROP TABLE to delete a table, but this command deletes the table structure as well; if you want to insert data, you need to recreate the table.

TRUNCATE TABLE has the same effect as DELETE, but it is faster because it does not actually scan the table. In addition, TRUNCATE TABLE can immediately free up table space without requiring a subsequent VACUUM operation, which is very useful for large tables.

The PostgreSQL VACUUM operation is used to release and reuse the disk space occupied by updated/deleted rows.

Syntax

The basic syntax of TRUNCATE TABLE is as follows:

TRUNCATE TABLE  table_name;

Example

Create the COMPANY table (Download the COMPANY SQL file ), with the following data:

runoobdb# 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 uses TRUNCATE TABLE to clear the COMPANY table:

runoobdb=# TRUNCATE TABLE COMPANY;

The result is as follows:

runoobdb=# SELECT * FROM CUSTOMERS;

 id | name | age | address | salary

----+------+-----+---------+--------

(0 rows)