87

I have a datetime field in my Postgresql, named "dt". I'd like to do something like

SELECT * FROM myTable WHERE extract (date from dt) = '01/01/11'

What is the right syntax to do that?

Thanks!

2 Answers 2

158

I think you want to cast your dt to a date and fix the format of your date literal:

SELECT *
FROM table
WHERE dt::date = '2011-01-01' -- This should be ISO-8601 format, YYYY-MM-DD

Or the standard version:

SELECT *
FROM table
WHERE CAST(dt AS DATE) = '2011-01-01' -- This should be ISO-8601 format, YYYY-MM-DD

The extract function doesn't understand "date" and it returns a number.

3
  • 14
    One addition: If the timestamp field is indexed, using dt::date or CAST(dt AS date) prevents the index from being used. An alternate method would be to either build a functional index on dt::date or to write it this way (using parameter $1 as a date string): WHERE dt >= $1 AND dt < $1 + interval '1 day'. May 5, 2011 at 16:44
  • whatever @MatthewWood says, is always right :)
    – sufinawaz
    Jan 12, 2022 at 21:25
  • works flawlessly!
    – Gaurav
    Feb 21, 2022 at 16:32
18

With PostgreSQL there are a number of date/time functions available, see here.

In your example, you could use:

SELECT * FROM myTable WHERE date_trunc('day', dt) = 'YYYY-MM-DD';

If you are running this query regularly, it is possible to create an index using the date_trunc function as well:

CREATE INDEX date_trunc_dt_idx ON myTable ( date_trunc('day', dt) );

One advantage of this is there is some more flexibility with timezones if required, for example:

CREATE INDEX date_trunc_dt_idx ON myTable ( date_trunc('day', dt at time zone 'Australia/Sydney') );
SELECT * FROM myTable WHERE date_trunc('day', dt at time zone 'Australia/Sydney') = 'YYYY-MM-DD';

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.