Sub topic 9
Using EXPLAIN ANALYZE on INSERT, UPDATE and DELETE safely
This chapter assumes you can read a basic plan tree and know what EXPLAIN ANALYZE adds (actual time, actual rows, loops). You should also be comfortable with transactions (BEGIN, COMMIT, ROLLBACK) in psql. The examples use PostgreSQL.
Why this needs its own chapter
Plain EXPLAIN only plans a statement. EXPLAIN ANALYZE plans it and then executes it. For a SELECT, that costs time and nothing else. For INSERT, UPDATE and DELETE, the statement really changes data.
-- This deletes rows. It is not a dry run.
EXPLAIN ANALYZE
DELETE FROM orders
WHERE created_at < DATE '2020-01-01';If you run that in psql with autocommit on, the rows are gone when the command returns. The plan is a report of what happened, not a preview.
The safe approach is to wrap the statement in a transaction and roll it back. The plan you get is accurate, and the row changes do not persist.
BEGIN;
EXPLAIN (ANALYZE)
UPDATE orders
SET status = 'archived'
WHERE created_at < DATE '2020-01-01';
ROLLBACK;If you only need the estimated plan, use plain EXPLAIN. It never executes the statement, so it is always safe for writes. Use ANALYZE only when you need real timings and real row counts.
The safe procedure
A complete, runnable version looks like this:
BEGIN;
SET LOCAL statement_timeout = '30s';
SET LOCAL lock_timeout = '2s';
EXPLAIN (ANALYZE, BUFFERS)
DELETE FROM orders
WHERE status = 'cancelled'
AND created_at < DATE '2022-01-01';
ROLLBACK;SET LOCAL lasts only until the end of the current transaction, so the timeouts do not leak into your session. The two timeouts matter for different reasons:
statement_timeoutstops a statement that turns out to be far slower than you guessed. The failed statement aborts the transaction, and you then runROLLBACK.lock_timeoutstops you from waiting behind another session's locks. Without it, your probe can queue behind a long transaction, and everyone else then queues behind your probe.
Always type BEGIN first. A common accident is to paste EXPLAIN ANALYZE UPDATE ... and a trailing ROLLBACK; while forgetting the BEGIN. The UPDATE has already committed by then, and the ROLLBACK only prints a warning.
You can lower this risk by turning autocommit off in psql for the session:
\set AUTOCOMMIT offWith autocommit off, psql starts a transaction implicitly before your first statement. You then end it with an explicit ROLLBACK or COMMIT.
Reading a data-modifying plan
A write statement appears in the plan as a top node named after the operation: Insert on, Update on or Delete on. Underneath it is the plan that finds the rows to change.
BEGIN;
EXPLAIN (ANALYZE)
UPDATE orders
SET status = 'archived'
WHERE customer_id = 42;
ROLLBACK;A plan for this might look like:
Update on orders (cost=4.67..120.30 rows=48 width=70) (actual time=0.412..0.413 rows=0 loops=1)
-> Bitmap Heap Scan on orders (cost=4.67..120.30 rows=48 width=70) (actual time=0.060..0.105 rows=52 loops=1)
Recheck Cond: (customer_id = 42)
Heap Blocks: exact=49
-> Bitmap Index Scan on orders_customer_id_idx (cost=0.00..4.66 rows=48 width=0) (actual time=0.041..0.041 rows=52 loops=1)
Index Cond: (customer_id = 42)
Planning Time: 0.150 ms
Execution Time: 0.470 msThree details trip people up:
- The top node reports
rows=0even though 52 rows changed. A write node reports the rows it returns, and without aRETURNINGclause it returns none. The number of rows affected is the actual row count of the scan node below it. - The scan below the write node is a normal read plan. Everything from earlier chapters applies to it: scan type, estimates versus actuals,
Rows Removed by Filter. - The time on the write node includes the time of its children plus the work of modifying heap pages, updating indexes and firing row-level triggers.
Trigger and constraint time
Triggers and foreign key checks run as part of the write. EXPLAIN ANALYZE lists them after the plan tree:
Trigger for constraint orders_customer_id_fkey: time=1.820 calls=1000
Trigger audit_orders_trg: time=45.300 calls=1000If the scan is fast but Execution Time is large, check these lines. A write that looks slow because of a missing index on a foreign key column, or because of an expensive audit trigger, shows its cost here and not in the scan nodes.
What a rollback does not undo
Rolling back removes the changed rows from view. It does not erase every trace of the statement. The table lists what persists.
| Effect of the executed statement | Undone by `ROLLBACK`? |
|---|---|
| Inserted, updated or deleted rows | Yes, they become invisible |
| Dead row versions left behind | No, they stay until `VACUUM` removes them |
| Sequence values used by `nextval` | No, the values are consumed |
| Row and table locks | Released at rollback, but held until then |
| Write-ahead log records | No, they are written and may be replicated |
| Cache contents | No, touched pages stay in memory |
| Side effects outside the database (HTTP calls from a function, writes through `dblink` to another database already committed) | No |
| Rows changed by triggers in the same database | Yes |
Sequence gaps are easy to demonstrate:
CREATE TABLE audit_demo (id bigserial PRIMARY KEY, note text);
BEGIN;
EXPLAIN (ANALYZE)
INSERT INTO audit_demo (note) VALUES ('probe');
ROLLBACK;
INSERT INTO audit_demo (note) VALUES ('real') RETURNING id;The final insert returns id = 2. The probe consumed value 1, and the rollback did not give it back. Gaps in a sequence are harmless in normal use, but you should not expect gap-free numbering on a table you have profiled this way.
Before you profile on production, consider these alternatives:
- Run the probe on a restored copy or a staging database with similar data volume and statistics.
- Probe with a narrower
WHEREclause on a small slice, then reason about how the cost scales. - Rewrite the write as a
SELECTthat uses the sameWHEREclause andEXPLAIN ANALYZEthat. The scan and join part of the plan will usually be identical. You will not see the write cost or trigger cost, but you will see whether the row-finding step is the problem.
-- Same row-finding work as the UPDATE above, with no writes.
EXPLAIN (ANALYZE, BUFFERS)
SELECT 1
FROM orders
WHERE customer_id = 42;Other cases to watch
- Data-modifying CTEs. A
WITH ... DELETE ... RETURNINGquery modifies data even though the outer statement is aSELECT.EXPLAIN ANALYZEexecutes it. Wrap it in a transaction too. - Functions with side effects. A
SELECTthat calls a volatile function that writes data, sends a notification or touches another system also runs that function underANALYZE. - Read-only transactions.
EXPLAIN ANALYZEon a write fails in aREAD ONLYtransaction or on a standby, because the statement would really execute. PlainEXPLAINstill works there. - Timing overhead. Per-node timing calls add overhead, which is noticeable on plans with millions of row visits.
EXPLAIN (ANALYZE, TIMING OFF)keeps row counts and totals and drops per-node timing. - Repeated runs. The second run of a probe often reads pages from cache that the first run loaded. Compare
BUFFERSoutput (shared hitversusread) before you conclude that a change made the statement faster. - A failed statement aborts the transaction. After an error, every further statement fails with "current transaction is aborted" until you run
ROLLBACK.
Checklist
- Do you need real timings? If not, use plain
EXPLAIN. - If you do, can you run it on a copy of the data?
- Open a transaction with
BEGIN, and setlock_timeoutandstatement_timeoutwithSET LOCAL. - Run
EXPLAIN (ANALYZE, BUFFERS)on the statement. - Read the scan nodes for row-finding cost and the trigger lines for side-work cost.
- End with
ROLLBACK, and expect consumed sequence values and dead tuples.
Exercise
A teammate runs EXPLAIN ANALYZE DELETE FROM sessions WHERE expires_at < now(); in psql with default settings and then types ROLLBACK;. Are the deleted rows restored? Why or why not?
Show answer
No. With autocommit on and no BEGIN, the DELETE ran in its own transaction and committed as soon as it finished. The later ROLLBACK has nothing to undo, and psql only warns that there is no transaction in progress. The statement should have been wrapped in BEGIN; ... ROLLBACK;.
Exercise
You profile an UPDATE ... WHERE customer_id = 42 with EXPLAIN ANALYZE and see Update on orders (actual time=0.412..0.413 rows=0 loops=1) above an index scan that returned 52 rows. How many rows did the statement change, and why does the top node show 0?
Show answer
It changed 52 rows. The Update on node reports the rows it outputs, and the statement has no RETURNING clause, so it outputs none. The rows affected are the actual rows of the scan node below it.
Exercise
After a rolled-back EXPLAIN ANALYZE INSERT into a table with a bigserial key, the next real insert gets id 2 instead of 1. Explain this and name one other effect that persists after the rollback.
Show answer
nextval is not transactional. The probe consumed value 1, and rolling back does not return sequence values. Other persistent effects include dead tuples that wait for VACUUM, WAL records already written, and pages that remain in cache.
Exercise
Your EXPLAIN (ANALYZE) of a DELETE shows a fast scan node but an Execution Time of 900 ms. Where in the output do you look next, and what are two likely causes?
Show answer
Look at the trigger lines listed after the plan tree, such as Trigger for constraint ...: time=... calls=.... Likely causes are an unindexed foreign key column on a referencing table (each deleted row triggers a slow lookup) and an expensive row-level trigger, such as an audit trigger.