实现说明
这个文件依次执行 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;