Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL: Create an index on timestamp::DATE [duplicate]

Tags:

I am creating a summary table that sums up all events in a given day.

INSERT INTO graph_6(   day,   event_type,   (SELECT COUNT(*) FROM event e                    WHERE event_type = e.event_type                    AND creation_time::DATE = sq.day) FROM event_type CROSS JOIN     (SELECT generate_series(                 (SELECT '2014-01-01'::DATE),                 (SELECT '2014-01-02'::DATE),                 '1 day') as day) sq; 

The creation_time column is indexed:

CREATE INDEX event_creation_time_date_idx ON event USING BTREE(creation_time); 

However, the query runs a pretty long time even when only querying two days of data with a handful of events (January 1-2 2014).

The EXPLAIN on the query is pretty grim - it runs a sequential scan on the event table, not utilizing the index at all:

->  Seq Scan on event e_1  (cost=0.00..12557.39 rows=531 width=38) Filter: ... AND ((creation_time)::date = (generate_series(($12)::timestamp with time zone, ($13)::timestamp with time zone, '1 day'::interval)))) 

I assume this is because we compare a casted value - creation_time::DATE, not creation_time. I have tried indexing the cast:

CREATE INDEX event_creation_time_date_idx ON event USING BTREE(creation_time::DATE); 

But got an error:

ERROR: syntax error at or near "::" 

Is there a way to utilize PostgreSQL indices on a timezone column casted to DATE?

like image 920
Adam Matan Avatar asked Jan 11 '16 14:01

Adam Matan


People also ask

Does create index lock table Postgres?

One downside of creating index after importing is that table must be locked, and that may take long time (it will not be locked in opposite scenario). But, in PostgreSQL 8.2 and later, you can use CREATE INDEX CONCURRENTLY, which does not lock table during indexing (with some caveats).

Can we create multiple index on same column PostgreSQL?

In PostgreSQL, you can create multiple indexes for a single column.

What is create index in PostgreSQL?

Description. CREATE INDEX constructs an index on the specified column(s) of the specified relation, which can be a table or a materialized view. Indexes are primarily used to enhance database performance (though inappropriate use can result in slower performance).

What is the format of timestamp in PostgreSQL?

Postgres DATE data type Postgres uses the DATE data type for storing different dates in YYYY-MM-DD format. It uses 4 bytes for storing a date value in a column. You can design a Postgres table with a DATE column and use the keyword DEFAULT CURRENT_DATE to use the current system date as the default value in this column.


1 Answers

An expression in an index declaration should be enclosed in additional brackets, try:

CREATE INDEX event_creation_time_date_idx ON event ((creation_time::DATE)); 
like image 191
klin Avatar answered Oct 10 '22 17:10

klin