Paste this into a new question or an answer at dba.stackexchange.com:
<!-- --> > CREATE TEMP TABLE tbl AS > SELECT (random() * 10000)::int AS lots > , (random() * 4)::int AS few > FROM generate_series (1, 100000); -- 100k rows > > DELETE FROM tbl WHERE random() > 0.9; -- create some dead tuples, more "real-life" > > <pre> 100000 rows affected > 10080 rows affected > </pre> <!-- --> > VACUUM ANALYZE tbl; > > <pre> > ✓ > </pre> <!-- --> > SELECT count(distinct lots) -- ~ 10000 > , count(distinct few) -- 5 > FROM tbl; > > SELECT * > FROM tbl > WHERE lots = 2345 > AND few = 2; > > <pre> > count | count > ----: | ----: > 9996 | 5 > > lots | few > ---: | --: > 2345 | 2 > </pre> <!-- --> > CREATE INDEX tbl_lf_idx ON tbl(lots, few); > > <pre> > ✓ > </pre> <!-- --> > EXPLAIN (ANALYZE, TIMING OFF) > SELECT * FROM tbl WHERE lots = 2345 AND few = 2; > > <pre> > | QUERY PLAN | > | :------------------------------------------------------------------------------------------------ | > | Index Only Scan using tbl_lf_idx on tbl (cost=0.29..4.33 rows=2 width=8) (actual rows=1 loops=1) | > | Index Cond: ((lots = 2345) AND (few = 2)) | > | Heap Fetches: 0 | > | Planning Time: 0.226 ms | > | Execution Time: 0.070 ms | > </pre> <!-- --> > -- repeat > EXPLAIN (ANALYZE, TIMING OFF) > SELECT * FROM tbl WHERE lots = 2345 AND few = 2; > > <pre> > | QUERY PLAN | > | :------------------------------------------------------------------------------------------------ | > | Index Only Scan using tbl_lf_idx on tbl (cost=0.29..4.33 rows=2 width=8) (actual rows=1 loops=1) | > | Index Cond: ((lots = 2345) AND (few = 2)) | > | Heap Fetches: 0 | > | Planning Time: 0.040 ms | > | Execution Time: 0.016 ms | > </pre> <!-- --> > DROP INDEX tbl_lf_idx; > CREATE INDEX tbl_fl_idx ON tbl(few, lots); > > <pre> > ✓ > > ✓ > </pre> <!-- --> > EXPLAIN (ANALYZE, TIMING OFF) > SELECT * FROM tbl WHERE lots = 2345 AND few = 2; > > <pre> > | QUERY PLAN | > | :------------------------------------------------------------------------------------------------ | > | Index Only Scan using tbl_fl_idx on tbl (cost=0.29..4.33 rows=2 width=8) (actual rows=1 loops=1) | > | Index Cond: ((few = 2) AND (lots = 2345)) | > | Heap Fetches: 0 | > | Planning Time: 0.214 ms | > | Execution Time: 0.069 ms | > </pre> <!-- --> > -- repeat > EXPLAIN (ANALYZE, TIMING OFF) > SELECT * FROM tbl WHERE lots = 2345 AND few = 2; > > <pre> > | QUERY PLAN | > | :------------------------------------------------------------------------------------------------ | > | Index Only Scan using tbl_fl_idx on tbl (cost=0.29..4.33 rows=2 width=8) (actual rows=1 loops=1) | > | Index Cond: ((few = 2) AND (lots = 2345)) | > | Heap Fetches: 0 | > | Planning Time: 0.041 ms | > | Execution Time: 0.017 ms | > </pre> *db<>fiddle [here](https://dbfiddle.uk/?rdbms=postgres_13&fiddle=ba11679f77b2da5ab218170326d338d3)*
back to fiddle