I have a table named "db_log" with a size of 11GB and approximately 10 million rows in PostgreSQL 13.7 version. The issue is that a simple query is not performing an full index scan for every column and takes around 15 seconds to complete. Here are the results when running the query using EXPLAIN ANALYZE:
EXPLAIN ANALYZE SELECT id, entity_id, request_json FROM db_log dl WHERE status = 'FAILED' AND db_type = 'SOME_VALUE' ORDER BY id DESC LIMIT 1;
QUERY PLAN
Limit (cost=0.43..1323.96 rows=1 width=673) (actual time=16343.062..16343.062 rows=0 loops=1)
-> Index Scan Backward using db_log_pkey on db_log dl (cost=0.43..1915136.79 rows=1447 width=673) (actual time=16343.061..16343.061 rows=0 loops=1)
Filter: (((status)::text = 'FAILED'::text) AND ((db_type)::text = 'SSM_SEND_XML_SKRIT'::text))
Rows Removed by Filter: 9471684
Planning Time: 0.429 ms
Execution Time: 16343.079 ms
(6 rows)
I have already created an index using the following query:
CREATE INDEX idx_combine_status_dbtype_id ON public.db_log USING btree (status, db_type, id);
DDL for that table:
CREATE TABLE public.db_log (
id bigserial NOT NULL,
db_type varchar(30) NULL DEFAULT 'NULL::character varying'::character varying,
entity_id varchar(200) NULL DEFAULT NULL::character varying,
request_json text NULL,
response_json text NULL,
time_submitted timestamp NULL,
time_request timestamp NULL,
time_response timestamp NULL,
created_by int4 NULL,
created_date timestamp NULL,
updated_by int4 NULL,
updated_date timestamp NULL,
status varchar(20) NULL DEFAULT 'NULL::character varying'::character varying,
url_db varchar(200) NULL,
CONSTRAINT db_log_pkey PRIMARY KEY (id)
);
CREATE INDEX combine_status_dbtype ON public.db_log USING btree (status, db_type);
CREATE INDEX combine_dbtype_entityid ON public.db_log USING btree (db_type, entity_id);
CREATE INDEX idx_combine_status_dbtype_id ON public.db_log USING btree (status, db_type, id);
CREATE INDEX idx_db_log_entity_id ON public.db_log USING btree (entity_id);
CREATE INDEX idx_db_log_status ON public.db_log USING btree (status);
CREATE INDEX idx_db_log_time_request ON public.db_log USING btree (time_request);
CREATE INDEX idx_db_log_time_response ON public.db_log USING btree (time_response);
CREATE INDEX idx_db_log_time_submitted ON public.db_log USING btree (time_submitted);
CREATE INDEX idx_db_log_db_type ON public.db_log USING btree (db_type);
What is the appropriate solution to address this issue?