[Solved] Postgres DISTINCT ON with index still sorts data

EverSQL Database Performance Knowledge Base

Postgres DISTINCT ON with index still sorts data

Database type:

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?

How to optimize this SQL query?

The following recommendations will help you in your SQL tuning process.
You'll find 3 sections below:

  1. Description of the steps you can take to speed up the query.
  2. The optimal indexes for this query, which you can copy and create in your database.
  3. An automatically re-written query you can copy and execute in your database.
The optimization process and recommendations:
  1. Create Optimal Indexes (modified query below): The recommended indexes are an integral part of this optimization effort and should be created before testing the execution duration of the optimized query.
Optimal indexes for this query:
CREATE INDEX demo_idx_key ON "demo" ("key");
The optimized query:
            ON (key) demo.key,
        demo.key IN (
            123, 443, 553

Related Articles

* original question posted on StackOverflow here.