I've got the sql query:
SELECT cast(AVG(SNR) AS integer) AS snr,
cast(AVG(RSSI) AS integer) AS rts
FROM SESSION
WHERE DATE(associationtime)>DATE(NOW()- INTERVAL '21 DAYS');
It works slow, because 21 days contains 300k rows.
Aggregate (cost=21768.07..21768.09 rows=1 width=8) (actual time=346.794..346.795 rows=1 loops=1)
-> Seq Scan on session (cost=0.00..20095.77 rows=334459 width=8) (actual time=0.014..282.512 rows=345304 loops=1)
Filter: (date(associationtime) > date((now() - '21 days'::interval)))
Rows Removed by Filter: 148508
Total runtime: 346.867 ms
How can I improve my query? May I create index or something?
UPD:
Index on associationtime
doesn't help.
postgres=# CREATE INDEX session_lim_values_idx ON session (associationtime);
CREATE INDEX
postgres=# EXPLAIN (ANALYZE) SELECT cast(AVG(SNR) as integer) as snr, cast(AVG(RSSI) as integer) as rts FROM session WHERE DATE(associationtime)>DATE(NOW()- INTERVAL '21 DAYS');
QUERY PLAN
-----------------------------------------------------------------------------------------------------------------------
Aggregate (cost=21768.07..21768.09 rows=1 width=8) (actual time=347.654..347.654 rows=1 loops=1)
-> Seq Scan on session (cost=0.00..20095.77 rows=334459 width=8) (actual time=0.014..283.344 rows=345304 loops=1)
Filter: (date(associationtime) > date((now() - '21 days'::interval)))
Rows Removed by Filter: 148508
Total runtime: 347.731 ms
And DATE(associationtime)
, too:
postgres=# CREATE INDEX session_lim_values_idx ON session (DATE(associationtime));
CREATE INDEX
postgres=# EXPLAIN (ANALYZE) SELECT cast(AVG(SNR) as integer) as snr, cast(AVG(RSSI) as integer) as rts FROM session WHERE DATE(associationtime)>DATE(NOW()- INTERVAL '21 DAYS');
QUERY PLAN
-----------------------------------------------------------------------------------------------------------------------
Aggregate (cost=21768.07..21768.09 rows=1 width=8) (actual time=341.050..341.050 rows=1 loops=1)
-> Seq Scan on session (cost=0.00..20095.77 rows=334459 width=8) (actual time=0.015..278.247 rows=345304 loops=1)
Filter: (date(associationtime) > date((now() - '21 days'::interval)))
Rows Removed by Filter: 148508
Total runtime: 341.129 ms