首页 > 解决方案 > How do I make 'SELECT COUNT(*) from clicks' faster?

问题描述

I'm using Postgres.

I have queries of the form:

`SELECT COUNT(*) from clicks where link_id=1`

Clicks is millions of rows.

These queries are taking 10-20 seconds.

Are there any elegant ways to accelerate this?

Edit: Query plan: enter image description here

Indexes

CREATE INDEX clicks_link_id_index
    ON public.clicks USING btree
    (link_id ASC NULLS LAST)
    TABLESPACE pg_default;
CREATE INDEX clicks_link_workspace_id_index
    ON public.clicks USING btree
    (link_workspace_id ASC NULLS LAST)
    TABLESPACE pg_default;
CREATE INDEX index_date_trunc
    ON public.clicks USING btree
    (date_trunc('day'::text, inserted_at) ASC NULLS LAST)
    TABLESPACE pg_default;

SET ENABLE_SEQSCAN TO OFF:

enter image description here

标签: postgresql

解决方案


它认为仅索引扫描将比顺序扫描便宜 4 倍,所以我很困惑为什么它没有首先选择仅​​索引扫描(在您设置 enable_seqscan=off 之前)。现在,如果您将其设置回默认值,它会再次使用 seq 扫描吗?

如果您刚刚对表进行 VACUUM,那么仅索引扫描会变得更快吗?虽然 99% 的行是在没有堆提取的情况下提取的,但其余 1% 可能占大部分时间。

或者也许你应该投入更多的硬件。拥有更多用于缓存数据的 RAM(在 shared_buffers 或文件系统缓存中)不会受到伤害。


推荐阅读