Question: Locks and schema changes
Does TRUNCATE lock the table?
Answered in the first paragraph. Last updated .
Yes, an access exclusive lock, on the named table and on every table the command cascades into. The work itself is quick, because it replaces the underlying files rather than removing rows one at a time, and the space comes back immediately with no vacuum needed. The exposure is the wait, not the work, and there is a second catch that has nothing to do with locking at all.
The catch that is not a lock
This command is documented as not being safe under snapshots. A transaction that took its view of the database before the truncation, and is still running, sees the table as empty rather than seeing the rows it was promised. Every other write in the system is invisible to such a reader until it commits; this one is not. A long-running report that overlaps a nightly truncate can therefore produce a clean, plausible, wrong answer.
What it does keep is transactional behaviour in the ordinary sense. Run it inside a transaction and roll back, and the rows are still there, including the sequence values if you asked for those to restart too. So the command can be staged safely; it just cannot be hidden from concurrent readers.
Cascading deserves a sentence of its own. By default the command refuses when another table references the target, which is the safe outcome. The cascade option makes it proceed by truncating the referencing tables as well, and the documentation’s own warning about losing data you did not intend to is the right level of alarm.
Choosing it over DELETE
The trade is simple once the two failures are named. Deleting every row takes weak locks and lets traffic continue, then leaves the whole table’s worth of space inside the file, which a delete never gives back. Truncating takes the heavy lock for a moment and returns the space at once.
On a busy table the heavy lock is the larger risk, and it is a risk of duration rather than of the command: the lock cannot be granted while any reader holds the table, so a two-minute query in front of it means two minutes during which nothing else can start either. Setting a lock timeout on the session that runs the truncate turns that into a fast failure you can retry.
Lock modes has the conflict grid, lock contention and blocking trees covers reading the queue when one has already formed, and the snapshot behaviour above only makes sense next to how versions are made visible in the first place.