postgresql - 按列为订单添加索引有什么好处?

标签 postgresql postgresql-11

我们有一个大表(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 的第一个行,因此不需要获取第一个并从那里开始顺序扫描以找到最后一个。

关于postgresql - 按列为订单添加索引有什么好处?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72232469/

相关文章:

python - 如何为 PostgreSQL 和 sqlite3 编写 psycopg2 的 SQL 语句?

sql-server-2008 - postgresql中如何编写索引查询

postgresql - 如何为PostgreSQL中的特定表提供写权限?

postgresql - 在postgres中更改用户定义的类型列类型

postgresql - Play Framework + Heroku + Postgres 无法连接

sql - 在 PostgreSQL 中的一个查询中更新具有不同主键的多行?

postgresql - 如何获得postgres中两个向量之间的余弦距离?

PostgreSQL 子查询案例顺序扫描

postgresql - Postgresql 中的存储过程中的表别名不存在架构

postgresql - PostgreSQL 11 中的逻辑复制和声明性分区