Slow query on ci_builds when searching for artifacts to remove
1) 1m13.895s - SELECT "ci_builds".* FROM "ci_builds" WHERE "ci_builds"."type" IN ('Ci::Build') AND (NOT (("ci_builds"."artifacts_file" = '' OR "ci_builds"."artifacts_file" IS NULL))) AND (artifacts_expire_at < '2016-10-07 05:17:14.267908') ORDER BY "ci_builds"."id" ASC LIMIT 50;
--
2) 1m13.831s - SELECT "ci_builds".* FROM "ci_builds" WHERE "ci_builds"."type" IN ('Ci::Build') AND (NOT (("ci_builds"."artifacts_file" = '' OR "ci_builds"."artifacts_file" IS NULL))) AND (artifacts_expire_at < '2016-10-07 05:17:14.252944') ORDER BY "ci_builds"."id" ASC LIMIT 50;
--
3) 1m13.728s - SELECT "ci_builds".* FROM "ci_builds" WHERE "ci_builds"."type" IN ('Ci::Build') AND (NOT (("ci_builds"."artifacts_file" = '' OR "ci_builds"."artifacts_file" IS NULL))) AND (artifacts_expire_at < '2016-10-07 05:17:14.245967') ORDER BY "ci_builds"."id" ASC LIMIT 50;
--
We are sorting by id, which is not necessary , and we are not using any actual index that makes sense here.
QUERY PLAN
------------------------------------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------
Limit (cost=0.00..718.21 rows=50 width=1399) (actual time=5465.130..5468.282 rows=50 loops=1)
-> Index Scan using ci_builds_pkey on ci_builds (cost=0.00..670034.38 rows=46646 width=1399) (actual time=5465.128..5468.225 rows=50 loops=1)
Filter: ((artifacts_file IS NOT NULL) AND (artifacts_file <> ''::text) AND (artifacts_expire_at < '2016-10-07 05:17:14.245967'::timestamp without t
ime zone) AND ((type)::text = 'Ci::Build'::text))
Rows Removed by Filter: 3983798
Total runtime: 5468.364 ms
Does this query even make any sense at all?