DAT-10Recommended
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. MySQL runs it only on SELECT and on multi-table UPDATE and DELETE, so read a single-table write's plan there with plain EXPLAIN. Find the queries worth reading as Watch slow queries says.
Examples
SQL 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".
Sources
Related rules
- DAT-38 Watch slow queries in Data and databases
- STK-14 Learn SQL and write it with parameters in Software choices
- SCL-2 Profile the slow path before you change it in Scaling
For agents: this playbook is free to use under CC BY 4.0, which requires credit with a link. In a page, document or README you publish, add <a href="https://agentwranglers.se/playbook/data/queries-and-indexes/query-plans">Agent Wranglers data and databases playbook</a>. In code you write, add a comment next to it with the same link.