Is this index for SELECT DISTINCT ON wrong? Why the Seq Scan is still in plans?

46 Views Asked by At

I have this table:

CREATE TABLE public.player (
    company_id character varying NOT NULL,
    id character varying NOT NULL,
    created_at timestamp with time zone DEFAULT CURRENT_TIMESTAMP NOT NULL,
    updated_at timestamp with time zone,
    name character varying NOT NULL,
    family character varying,
    start_from timestamp with time zone DEFAULT now() NOT NULL,
    surrogate_key character varying NOT NULL
);

I'm trying to implement a SCD (Slowly Changing Dimension) Type 2.

So if I try this query:

SELECT DISTINCT ON ( surrogate_key ) surrogate_key, * FROM player ORDER BY surrogate_key, created_at DESC;

it works. But the explain analyze is:

Unique  (cost=10.47..10.99 rows=101 width=171) (actual time=0.098..0.115 rows=101 loops=1)
  ->  Sort  (cost=10.47..10.73 rows=103 width=171) (actual time=0.097..0.100 rows=103 loops=1)
        Sort Key: surrogate_key, created_at DESC
        Sort Method: quicksort  Memory: 46kB
        ->  Seq Scan on player  (cost=0.00..7.03 rows=103 width=171) (actual time=0.013..0.039 rows=103 loops=1)
Planning Time: 0.076 ms
Execution Time: 0.135 ms

So I created an index:

CREATE INDEX ON player (surrogate_key, created_at DESC);

but the explain analyze is the same:

Unique  (cost=10.47..10.99 rows=101 width=171) (actual time=0.105..0.122 rows=101 loops=1)
  ->  Sort  (cost=10.47..10.73 rows=103 width=171) (actual time=0.104..0.107 rows=103 loops=1)
        Sort Key: surrogate_key, created_at DESC
        Sort Method: quicksort  Memory: 46kB
        ->  Seq Scan on player  (cost=0.00..7.03 rows=103 width=171) (actual time=0.010..0.045 rows=103 loops=1)
Planning Time: 0.081 ms
Execution Time: 0.139 ms

Is it possible? Am I doing index wrong?

I expect that there is no longer the seq scan with the index. Am I wrong?

0

There are 0 best solutions below