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.

SqlData Fetching

Code

snippet
-- 混合方向排序: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

FAQ

Which relations are involved here?
`events` — referenced directly, no join needed.