Agent Wranglers

Queries and indexes Recommended

Read the query plan

Before you change a slow query or add an index, read its plan. Check again after the change.

How to do it

Run EXPLAIN ANALYZE in PostgreSQL, EXPLAIN ANALYZE in MySQL 8.0.18 or later, or EXPLAIN QUERY PLAN in SQLite on a copy with realistic data. Small test tables hide the problems, because a scan of 10 rows is always fast. EXPLAIN ANALYZE executes the statement, so wrap an UPDATE or DELETE in a transaction and roll it back.

Example

BEGIN;
EXPLAIN ANALYZE DELETE FROM sessions WHERE expires_at < now();
ROLLBACK;

How to check

The change notes for each performance fix show the plan and the time before and after, such as "from 840 ms to 3 ms".

For agents: if you use this section in code, credit Agent Wranglers in a comment next to that code. Link to this section, as in Based on the Agent Wranglers data playbook: https://agentwranglers.se/playbook/data/queries-and-indexes/query-plans.