EXPLAIN ANALYZE Index Usage Plans
Diagnose slow queries with EXPLAIN ANALYZE and BUFFERS, reading scans, join strategies, and actual row estimates.
Code
-- BUFFERS 选项显示磁盘与缓存命中,真实成本的核心
EXPLAIN (ANALYZE, BUFFERS)
SELECT o.id, c.email
FROM orders o
JOIN customers c ON c.id = o.customer_id
WHERE o.status = 'paid'
AND o.created_at >= '2026-10-01'
ORDER BY o.created_at DESC
LIMIT 50;
-- 检查估算偏差:预估行数与实际行数差距大时统计信息过期
EXPLAIN (ANALYZE)
SELECT count(*)
FROM orders
WHERE customer_id = 42;
-- 统计信息刷新后重测
ANALYZE orders;
EXPLAIN (ANALYZE)
SELECT count(*)
FROM orders
WHERE customer_id = 42;
-- 验证新索引被采用:Index Scan / Index Only Scan
CREATE INDEX CONCURRENTLY idx_orders_customer_status
ON orders (customer_id, status);
EXPLAIN (ANALYZE)
SELECT id FROM orders
WHERE customer_id = 42 AND status = 'paid';What the code does
Several statements share this file — SELECT / CREATE / EXPLAIN, with orders and customers among the objects involved.
In terms of clauses, the statements use: one JOIN combining rows across tables; a WHERE clause deciding which rows the statement applies to; COUNT aggregation; an ORDER BY that fixes the output order; a row cap (LIMIT) bounding the result size.
Applying it
Run it in the orders database context; the LIMIT keeps each attempt cheap.
Statements that matter
EXPLAIN (ANALYZE, BUFFERS)
SELECT o.id, c.email
FROM orders o
JOIN customers c ON c.id = o.customer_id
WHERE o.status = 'paid'
AND o.created_at >= '2026-10-01'
ORDER BY o.created_at DESC
LIMIT 50;
EXPLAIN (ANALYZE)
SELECT id FROM orders
WHERE customer_id = 42 AND status = 'paid';
EXPLAIN (ANALYZE)
SELECT count(*)
FROM orders
WHERE customer_id = 42;
Interactive Tools for This Topic
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.DSN Connection String ParserParse PostgreSQL, MySQL, Redis, MongoDB, and AMQP DSN URLs locally with masked credentials, multi-host support, default ports, and SSL/pool inspection.HAR Waterfall AnalyzerInspect HTTP Archive (HAR 1.2) JSON files locally to summarize total requests, status codes, MIME types, slowest calls, and timing waterfalls.
FAQ
- What are the relations in play here?
- `orders`, `customers` — joined via one JOIN clause.
Report a problem with this exampleOpens a pre-filled issue on GitHub.