为按列排序添加索引有好处吗?

Benefit to adding an Index for an order by column?

我们有一个很大的 table(280 万行),我们在 device_token

中找到了一行
CREATE TABLE public.rpush_notifications (
    id bigint NOT NULL,
    device_token character varying,
    data text,
    created_at timestamp without time zone NOT NULL,
    updated_at timestamp without time zone NOT NULL,
...

我们一直在做以下查询:

SELECT * FROM rpush_notifications WHERE device_token = '...' ORDER BY updated_at DESC LIMIT 1

我想为我们的 device_token 列添加一个索引,我想知道为 updated_at 创建一个额外的索引或为两者创建一个多列索引是否有任何好处列 device_tokenupdated_at 鉴于我们正在排序,即:

CREATE INDEX foo ON rpush_notifications(device_token, updated_at)

我一直无法找到一个答案来帮助我理解在给定上面 运行 的查询的情况下将 updated_at 添加到索引是否会有任何性能优势。任何帮助表示赞赏。我们是 运行 Postgresql11

如果您像 ((device_token, updated_at)) 那样合并两列,则会带来性能优势,因为数据库可以轻松找到具有特定 device_token 的条目,而无需这样做查询期间的排序。

更好的做法是在 (device_token, updated_at DESC) 上建立索引,因为它会将请求的行作为此 device_token 的第一行,因此无需获取第一行并开始顺序扫描从那里找到最后一个。