The TRUNCATE TABLE
command in PostgreSQL is used to delete all the rows in a table. It is a DELETE
command because it does not need to scan the table. Instead, the TRUNCATE TABLE
simply drops the entire table and then just recreates the structure.
The DELETE
command is useful in cases when only certain data, that matches some conditions, need to be deleted. This command scans the table row-by-row to find all the contents that match the specified condition.
The TRUNCATE TABLE
command deletes all the data from a table in one go. It does not even need to perform a vacuum operation afterward as the storage is reclaimed immediately. With this command, a WHERE
clause cannot be specified.
To remove the data from one table, the following command is used:
TRUNCATE TABLE table_name;
After executing the above command, if you try to select any data from the table, it will not return any rows.
To remove the data from multiple tables, the syntax is as follows:
TRUNCATE TABLE table1, table2, table3;
The table contents that you wish to delete may have some foreign key references and, by default, this data is not deleted with the TRUNCATE TABLE
command. To remove such data, you need to explicitly mention it using the CASCADE
keyword:
TRUNCATE TABLE table_nameCASCADE;
This command does not fire the ON DELETE
triggers even though it does delete the data. Only BEFORE
/AFTER TRUNCATE
triggers may be fired if defined.
TRUNCATE TABLE
is transaction safe so, if it is performed inside a transaction that is rolled back, the data is also rolled back.