SQL

EXPLAIN / EXPLAIN ANALYZE

admin by @admin ADMIN
Jun 13, 2026
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
`EXPLAIN` shows the query plan; `EXPLAIN ANALYZE` actually runs it and shows real timings. The first tool when a query is slow — look for sequential scans on big tables.
SQL
Raw
-- Show the plan (does NOT run the query)
EXPLAIN
SELECT u.email, COUNT(o.id) AS order_count
FROM   users u
LEFT   JOIN orders o ON o.user_id = u.id
WHERE  u.status = 'active'
GROUP  BY u.email;

-- ACTUALLY RUN and show timings (PostgreSQL)
EXPLAIN (ANALYZE, BUFFERS, FORMAT TEXT)
SELECT * FROM orders WHERE user_id = 42 AND created_at >= NOW() - INTERVAL '7 days';

-- Things to look for in the output:
--   Seq Scan on big_table          ← bad if it's filtering most rows out
--   Index Scan using idx_xyz       ← good
--   Index Only Scan                ← great (no heap touch)
--   Rows Removed by Filter: 99000  ← index isn\'t selective enough
--   Sort  Method: external merge   ← work_mem too small; sort spilled to disk
--   Hash Join / Nested Loop / Merge Join — choice depends on row counts

-- MySQL — EXPLAIN or EXPLAIN FORMAT=JSON or EXPLAIN ANALYZE (8.0+)
EXPLAIN FORMAT=JSON
SELECT * FROM users WHERE email = 'alice@x.com';
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.