Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL: Select data with a like on timestamp field

I am trying to select data from a table, using a "like" on date field "date_checked" (timestamp). But I have this error :

SQLSTATE[42883]: Undefined function: 7 ERROR:  operator does not exist: timestamp without time zone 

My request is :

SELECT my_table.id FROM my_table WHERE my_table.date_checker LIKE '2011-01-%' 

I don't want to use :

SELECT my_table.id FROM my_table WHERE my_table.date_checker >= '2011-01-01 00:00:00'      AND  my_table.date_checker < '2011-02-01 00:00:00' 
like image 425
Kevin Campion Avatar asked Jan 25 '11 22:01

Kevin Campion


People also ask

How do I query a timestamp column in PostgreSQL?

PostgreSQL timestamp example First, create a table that consists of both timestamp the timestamptz columns. Next, set the time zone of the database server to America/Los_Angeles . After that, query data from the timestamp and timestamptz columns. The query returns the same timestamp values as the inserted values.

Can we use like for timestamp in SQL?

Like operator will not work with DateTime.

How do I compare two timestamps in PostgreSQL?

To calculate the difference between the timestamps in PostgreSQL, simply subtract the start timestamp from the end timestamp. Here, it would be arrival - departure . The difference will be of the type interval , which means you'll see it in days, hours, minutes, and seconds.

How do I use like keyword in PostgreSQL?

The PostgreSQL LIKE operator is used to match text values against a pattern using wildcards. If the search expression can be matched to the pattern expression, the LIKE operator will return true, which is 1. The percent sign represents zero, one, or multiple numbers or characters.


2 Answers

It's all very well not "wanting to use" < and > with timestamps, but those operators can be converted into index scans, and a string-match... well, it can, but EWWWW.

Well, the error is occurring because you need to explicitly convert the timestamp to a string before using a string operation on it, e.g.:

date_checker::text LIKE '2011-01-%' 

and I suppose you could then create an index on (date_checker::text) and that expression would become an index scan but.... EWWWW.

like image 86
araqnid Avatar answered Oct 08 '22 14:10

araqnid


Try this:

SELECT my_table.id FROM my_table WHERE CAST(my_table.date_checker AS VARCHAR) LIKE '2011-01-%'; 
like image 32
KUMAR AYYAPPA Avatar answered Oct 08 '22 13:10

KUMAR AYYAPPA