What is the difference between DELETE and TRUNCATE in PostgreSQL? Can DELETE be rolled back without a transaction?
sobes.tech AI
Answer from AI
In PostgreSQL:
-
DELETE removes rows from a table based on a condition, and each deleted row is recorded in the transaction log (WAL), allowing the operation to be rolled back within a transaction. DELETE can be slower with large volumes of data.
-
TRUNCATE quickly removes all rows from a table, effectively resetting its contents. It is a DDL operation that does not scan rows or generate individual records for each deleted row, so it works faster. TRUNCATE cannot be rolled back if executed outside a transaction, and it resets identity counters.
Can you roll back a DELETE without a transaction? No. In PostgreSQL, all data modifications, including DELETE, occur within a transaction. If you haven't explicitly started a transaction, each command runs in its own transaction (autocommit). After executing a DELETE without an explicit transaction, rollback is impossible because the transaction is already committed.