![]() |
VOOZH | about |
When working with large datasets in PostgreSQL, you might find the need to clear all data from a table quickly. While the DELETE statement is a common option, it can be slow when dealing with a table containing large amounts of data. Instead, PostgreSQL provides the TRUNCATE TABLEstatement, which is significantly faster and more efficient.
Let us get a better understanding of the TRUNCATE TABLE Statement in PostgreSQL from this article.
The TRUNCATE TABLE statement is used to instantly remove all rows from one or more tables. Unlike the DELETE statement, which removes rows one at a time and logs individual row deletions, TRUNCATE TABLE operates by deallocating the table's storage space directly, making it a much faster operation. It’s an ideal choice when you want to reset a table to its empty state without worrying about the overhead of row-by-row deletion.
TRUNCATE TABLE table_name;
The TRUNCATE TABLE statement does not care about the table while deleting the same, simultaneously clearing the space for use by the user.
Let us look at an example of the TRUNCATE TABLE in PostgreSQL to better understand the concept.
First list all tables in the database using the below command:
\dt
This will list all tables as depicted below:
👁 PostgreSQL TRUNCATE TABLE ExampleThe following example uses the TRUNCATE TABLE statement to delete all data from the 'foo' table:
TRUNCATE TABLE foo;
Now if checked for the table again it will show that all data in the table is deleted as shown below:
SELECT * FROM foo;
Output:
👁 PostgreSQL TRUNCATE TABLE Example