实现说明
一个文件里不止一条语句:SELECT / CREATE,sessions 都在涉及之列。
用到的 SQL 构件:ORDER BY 固定了输出顺序;LIMIT 限制返回行数。
常见问题
这些语句涉及哪些表?
引用的是 sessions。
核心语句
CREATE INDEX idx_sessions_started_desc_nulls_last
ON sessions (started_at DESC NULLS LAST);
SELECT id, started_at
FROM sessions
ORDER BY started_at DESC NULLS LAST
LIMIT 10;
CREATE INDEX idx_sessions_started_desc
ON sessions (started_at DESC);
代码示例
-- PG treats NULL as largest by default: ASC defaults to NULLS LAST, DESC to NULLS FIRST
-- A query wanting DESC NULLS LAST does not match a plain (started_at DESC) index's sort specification
CREATE INDEX idx_sessions_started_desc
ON sessions (started_at DESC);
-- This query falls back to a Sort node (or a seq scan on small tables):
-- SELECT id, started_at FROM sessions
-- ORDER BY started_at DESC NULLS LAST LIMIT 10;
-- Declare NULLS LAST at index creation so the column sort spec matches the ORDER BY exactly
CREATE INDEX idx_sessions_started_desc_nulls_last
ON sessions (started_at DESC NULLS LAST);
SELECT id, started_at
FROM sessions
ORDER BY started_at DESC NULLS LAST
LIMIT 10;