Mixed Sort Direction Index
Match index column directions to a mixed ORDER BY created_at DESC, id ASC so Top-N queries skip the Sort node entirely.
Code
-- 混合方向排序:ORDER BY created_at DESC, id ASC
-- 反向扫描会整体反转索引所有列的方向,覆盖不了混合方向;
-- 索引列方向必须与 ORDER BY 一一对应,Top-N 才能免 sort 直接出前 20 行
CREATE INDEX idx_events_feed
ON events (created_at DESC, id ASC);
EXPLAIN
SELECT event_id, created_at
FROM events
ORDER BY created_at DESC, id ASC
LIMIT 20;
-- 对比:全同向 (DESC, DESC) 用普通 (created_at, id) 索引反向扫描即可,
-- 混合方向才必须显式声明列方向;方向不匹配时规划器退回 Sort 节点再 LIMIT
-- 随数据量增长,成本线性上升How it works
Several statements share this file — SELECT / CREATE / EXPLAIN, with events among the objects involved.
Breaking the statements into their working parts: an ORDER BY that fixes the output order; a row cap (LIMIT) bounding the result size.
Putting it to use
Run the statement against the events table; the LIMIT keeps the probe cheap while you tune the predicates.
Core lines
EXPLAIN
SELECT event_id, created_at
FROM events
ORDER BY created_at DESC, id ASC
LIMIT 20;
CREATE INDEX idx_events_feed
ON events (created_at DESC, id ASC);
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.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.Line SorterSort text lines ascending or descending with numeric-aware ordering, duplicate removal, empty-line filtering, and locale-aware comparison.
FAQ
- Which relations are involved here?
- `events` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.