sql - Postgres where query optimization -


in our database have table menus having 515502 rows. has column status of type smallint.

currently, simple count query takes 700 ms set of docs having value of status 3.

explain analyze select count(id) menus status = 2; aggregate  (cost=72973.71..72973.72 rows=1 width=4) (actual time=692.564..692.565 rows=1 loops=1) ->  bitmap heap scan on menus  (cost=2510.63..72638.80 rows=133962 width=4) (actual time=28.179..623.077 rows=135429 loops=1)          recheck cond: (status = 2)          rows removed index recheck: 199654          ->  bitmap index scan on menus_status  (cost=0.00..2477.14 rows=133962 width=0) (actual time=26.211..26.211 rows=135429 loops=1)                index cond: (status = 2)  total runtime: 692.705 ms (7 rows) 

some rows have column value of 1 query runs fast.

 explain analyze select count(id) menus status = 4;                                                           query plan                                                            -------------------------------------------------------------------------------------------------------------------------------  aggregate  (cost=7198.73..7198.74 rows=1 width=4) (actual time=24.926..24.926 rows=1 loops=1)    ->  bitmap heap scan on menus  (cost=40.53..7193.53 rows=2079 width=4) (actual time=1.461..23.418 rows=2220 loops=1)          recheck cond: (status = 4)          ->  bitmap index scan on menus_status  (cost=0.00..40.02 rows=2079 width=0) (actual time=0.858..0.858 rows=2220 loops=1)                index cond: (status = 4)  total runtime: 25.089 ms (6 rows) 

i observed general btree index best indexing strategy simple equality based queries. both gin , hash slower btree.

any tips making count queries faster filter using index?

i understand beginner level question, apologies in advance kind of mistakes might have made.

maybe table has more rows having status = 2 ones having status = 4 , so, total table access time more second case. so, status = 2 there many rows consider, the bitmap bitmap heap scan goes "lossy" mode, , recheck needed after operation. so, there 2 things consider: either result big (but can't without reorganizing tables, say, partitioning), or 'work_mem' param small keep intermittent result. try increase value if have possibility.


Comments

Popular posts from this blog

python - No exponential form of the z-axis in matplotlib-3D-plots -

php - Best Light server (Linux + Web server + Database) for Raspberry Pi -

c# - "Newtonsoft.Json.JsonSerializationException unable to find constructor to use for types" error when deserializing class -