← 中文资源

简体中文版本

一条索引完成过滤排序限量

(status, created_at) 等值列在前、排序列在后:WHERE、ORDER BY、LIMIT 三件事由同一条复合索引一次读完,不需要额外排序节点。

阅读英文原文

实现说明

这个文件依次执行 SELECT / CREATE 语句,涉及 orders。 机制上由这些部分组成:WHERE 只放行满足条件的行进入这条语句;ORDER BY 固定了输出顺序;LIMIT 限制返回行数;必填列上的 NOT NULL 限定;强制行身份的 PRIMARY KEY;自动算列值的 GENERATED ALWAYS/GENERATED BY 子句。

常见问题

这段 SQL 涉及哪些对象?

orders。

核心语句

SELECT order_id, created_at
FROM orders
WHERE created_at > now() - interval '1 day'
ORDER BY created_at DESC, status
LIMIT 20;
SELECT order_id, created_at
FROM orders
WHERE status = 'pending'
ORDER BY created_at DESC
LIMIT 20;
CREATE TABLE orders (
    order_id   int GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    status     text NOT NULL,
    created_at timestamptz NOT NULL
);

代码示例

-- one composite index serves filter, sort, and limit in a single pass
-- (status, created_at): equality filter column first, sort column second
CREATE TABLE orders (
    order_id   int GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    status     text NOT NULL,
    created_at timestamptz NOT NULL
);
CREATE INDEX orders_status_created_idx ON orders (status, created_at DESC);

-- filter, sort and limit all come from the index: no separate sort step
SELECT order_id, created_at
FROM orders
WHERE status = 'pending'
ORDER BY created_at DESC
LIMIT 20;

-- counterexample: a range column ahead of the leading one or mixed directions leaves the index partially usable and the rest falls back to sorting
SELECT order_id, created_at
FROM orders
WHERE created_at > now() - interval '1 day'
ORDER BY created_at DESC, status
LIMIT 20;