Indexes and Explain
Speed reads with indexes and verify with EXPLAIN. Results appear in the same fence: same-line -- comments when short, multiline -- blocks below the sample when not.
Busca en todas las páginas de la documentación
Speed reads with indexes and verify with EXPLAIN. Results appear in the same fence: same-line -- comments when short, multiline -- blocks below the sample when not.
Default B-tree for equality and range.
CREATE INDEX idx_users_email ON users (email);
-- speeds WHERE email = ...Index only hot rows.
CREATE INDEX idx_orders_open ON orders (created_at)
WHERE status = 'open';
-- smaller index for open ordersIndex a computed expression.
CREATE INDEX idx_users_lower_email ON users (lower(email));
-- WHERE lower(email) = 'a@b.co'Run the plan and show actual times.
EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM orders WHERE user_id = 1;
-- plan + actual rows/timeNon-key columns for index-only scans.
CREATE INDEX idx_orders_user ON orders (user_id) INCLUDE (total);
-- SELECT total WHERE user_id = ? may avoid heapEnforce uniqueness (also creates a constraint path).
CREATE UNIQUE INDEX uq_users_email ON users (email);Build without long write locks.
CREATE INDEX CONCURRENTLY idx_events_ts ON events (ts);
-- cannot run in a transaction blockIndex jsonb containment queries.
CREATE INDEX idx_doc ON docs USING gin (body jsonb_path_ops);
-- WHERE body @> '{"type":"x"}'Inspect indexes on a table.
SELECT indexname, indexdef
FROM pg_indexes
WHERE tablename = 'orders';
-- index catalog rowsRemove unused indexes.
DROP INDEX CONCURRENTLY IF EXISTS idx_old;Multiple indexes can combine via bitmap heap scan - check EXPLAIN.
EXPLAIN SELECT * FROM t WHERE a = 1 AND b = 2;
-- may show BitmapAndAll needed columns in index + visibility map.
EXPLAIN SELECT user_id FROM orders WHERE user_id = 1;
-- Index Only Scan if possibleSession-only testing - never production default.
SET enable_seqscan = off;
EXPLAIN SELECT * FROM t WHERE id = 1;
-- forces index if availableRebuild bloated indexes.
REINDEX INDEX CONCURRENTLY idx_users_email;Explain without running (no ANALYZE).
EXPLAIN SELECT count(*) FROM big;
-- estimated costs onlyStack versions: PostgreSQL 18.4 (stable 18, maintenance 17) · pgvector 0.8+
Revisado por Chris St. John·Última actualización: 18 jul 2026