For a website that displays recent news, I have this query on the home page:
SELECT *
FROM "cms_news"
WHERE
NOT ("cms_news"."timestamp" >= '2013-08-08 13:32:39.778988+00:00') AND
"cms_news"."state" = 'published'
ORDER BY "cms_news"."flash" DESC, "cms_news"."timestamp" DESC LIMIT 7;
Here's the table definition:
CREATE TABLE cms_news (
id integer DEFAULT nextval('cms_news_id_seq'::regclass) NOT NULL,
created timestamp with time zone NOT NULL,
modified timestamp with time zone NOT NULL,
title character varying(510) NOT NULL,
text text NOT NULL,
"timestamp" timestamp with time zone NOT NULL,
state character varying(20) NOT NULL,
flash boolean NOT NULL,
);
With about 67000 entries in the table, the above query to select the newest 7 published news entries takes about 100ms, which seems a bit much. Here's the output of EXPLAIN
:
EXPLAIN SELECT * FROM "cms_news" WHERE (NOT ("cms_news"."timestamp" >= '2013-08-08 13:32:39.778988+00:00' ) AND "cms_news"."state" = 'published' ) ORDER BY "cms_news"."flash" DESC, "cms_news"."timestamp" DESC LIMIT 7;
QUERY PLAN
-------------------------------------------------------------------------------------------------------------------------------------------
Limit (cost=13600.34..13600.36 rows=7 width=1274)
-> Sort (cost=13600.34..13768.27 rows=67171 width=1274)
Sort Key: flash, "timestamp"
-> Seq Scan on cms_news (cost=0.00..12321.62 rows=67171 width=1274)
Filter: (("timestamp" < '2013-08-08 15:32:39.778988+02'::timestamp with time zone) AND ((state)::text = 'published'::text))
I'm a complete amateur (as you might have guessed already), but it looks like sorting is the real problem. What kind of index would help me here?
NOW()
. The system allows entering news entries with a future publishing date, those are filtered out. – Benjamin Wohlwend Aug 8 '13 at 14:19