A table with ~15 million rows.
Columns key, key2, timestamp.
Index on key, timestamp DESC NULLS LAST
SELECT DISTINCT ON (key) key, key2 FROM demo WHERE key IN (123, 443, 553)
'key' is not unique and there can be multiple duplicates of it.
I would have thought that a index with sorting would already be enough, yet explain still shows it - even if i specify GROUP BY - it's still there.
EXPLAIN: uses correct index -> bitmap heap scan -> sort -> unique
It is quite costly to have it sort the massive table before getting unique values.
Did i create index in a wrong way?
The following recommendations will help you in your SQL tuning process.
You'll find 3 sections below:
CREATE INDEX demo_idx_key ON "demo" ("key");
SELECT
DISTINCT
ON (key) demo.key,
demo.key2
FROM
demo
WHERE
demo.key IN (
123, 443, 553
)