Thread: Queries with timestamps
Hi all, I'm quite newbie in SQL and I have a performance problem. I have the following table (with some extra fields) and without any index: CREATE TABLE STATISTICS ( STATISTIC_ID NUMERIC(10) NOT NULL DEFAULT nextval('STATISTIC_ID_SEQ') CONSTRAINT pk_st_statistic_id PRIMARY KEY, TIMESTAMP_IN TIMESTAMP, VALUE NUMERIC(10) ); The queries on this table are mainly related with the timestamp field, e.g.: select * from statistics where time::date < current_date - interval '1 month'; As the number of rows grows the time needed to execute this query takes longer. What'd I should do improve the performance of this query? Thank you very much -- Arnau
Arnau, > As the number of rows grows the time needed to execute this query takes > longer. What'd I should do improve the performance of this query? Tip #1) add an index to the timestamp column Tip #2) make sure that you VACUUM and ANALYZE regularly Tip #3) You will get better performance if you pass the "current_date - 1 month" as a constant from the client instead of in the query. This is a known issue, expected to be fixed in 7.5. -- -Josh Berkus Aglio Database Solutions San Francisco
On Wednesday 21 January 2004 19:06, Josh Berkus wrote: > Arnau, > > > As the number of rows grows the time needed to execute this query > > takes longer. What'd I should do improve the performance of this query? > > Tip #1) add an index to the timestamp column > Tip #2) make sure that you VACUUM and ANALYZE regularly > Tip #3) You will get better performance if you pass the "current_date - 1 > month" as a constant from the client instead of in the query. This is a > known issue, expected to be fixed in 7.5. (I think Tip 3 is already fixed in 7.3, or I misunderstand what Josh is saying) Note that this is timestamp-related and not "timestamp with time zone" related. Most of the time you want the latter anyway. If you can use with time zones and drop the cast you might well find the index is being used... EXPLAIN ANALYSE SELECT * FROM log_core WHERE log_ts > CURRENT_DATE - '1 week'::interval; QUERY PLAN ----------------------------------------------------------------------------------------------------------------------------- Index Scan using log_core_ts_idx on log_core (cost=0.00..18.73 rows=239 width=117) (actual time=0.79..0.79 rows=0 loops=1) Index Cond: (log_ts > ((('now'::text)::date - '7 days'::interval))::timestamp with time zone) Total runtime: 1.03 msec (3 rows) It seems to help an accurate estimate of number-of-rows if you put an upper and lower limit in. -- Richard Huxton Archonet Ltd
Richard, > (I think Tip 3 is already fixed in 7.3, or I misunderstand what Josh is > saying) Yeah? Certainly looks like it. Apparently I can't keep track. I'd swear that this issue reared its ugly head again shortly before the 7.4 release. -- -Josh Berkus Aglio Database Solutions San Francisco