I have one table accounts
and indexes
accounts {
id text
num_id bigint
pid text
fid text
created_at timestamp with time zone
updated_at timestamp with time zone
}
CREATE UNIQUE INDEX accounts_pkey ON public.accounts USING btree (id)
CREATE INDEX fid_idx ON public.accounts USING btree (fid)
CREATE INDEX idx_accounts_pid_fid ON public.accounts USING btree (pid, fid)
And this query is slow
explain analyse SELECT * FROM accounts
WHERE pid = 'hd' AND fid = '123'
ORDER BY id ASC
LIMIT 1;
Limit (cost=0.56..3173.34 rows=1 width=123) (actual time=49389.351..49389.351 rows=0 loops=1)
-> Index Scan using accounts_pkey on accounts (cost=0.56..5022497.13 rows=1583 width=123) (actual time=49389.350..49389.350 rows=0 loops=1)
Filter: ((pid = 'hd'::text) AND (fid = '123'::text))
Rows Removed by Filter: 56821193
Planning time: 0.094 ms
Execution time: 49389.368 ms
Per this answer, it may be solved by adding unneeded where condition pid
and fid
explain analyse SELECT * FROM accounts
WHERE pid = 'hd' AND fid = '123'
ORDER BY id ASC, pid, fid
LIMIT 1;
However, it does not work
Limit (cost=0.56..3173.37 rows=1 width=123) (actual time=49495.236..49495.236 rows=0 loops=1)
-> Index Scan using accounts_pkey on accounts (cost=0.56..5022556.07 rows=1583 width=123) (actual time=49495.234..49495.234 rows=0 loops=1)
Filter: ((pid = 'hd'::text) AND (fid = '123'::text))
Rows Removed by Filter: 56821555
Planning time: 0.096 ms
Execution time: 49495.253 ms
Is there I am missing?
PostgreSQL version: 9.6.8