How to use DAY function in PostgreSQL database?

1.1k views Asked by At

I have this query for MySQL database:

Article.where('DAY( created_at ) = DAY( ? )', day)

And I try to use the query above also in the PostgreSQL database, specifically I am trying something like this:

Article.where("DATE_PART('day', created_at) = DATE_PART('day', ?)", today)

But I am getting the error PGError: ERROR: function date_part(unknown, unknown) is not unique

Why is there that error? I thought I have the syntax by documentation...

2

There are 2 answers

0
Erwin Brandstetter On BEST ANSWER

It seems today is a string of the pattern YYYY-MM-DD. You could just extract the rightmost two characters, instead of casting to date and then extracting a number. Would be faster and simpler:

Article.where("date_part('day', created_at::date)::int
                        = right(?, 2)::int", today)

right() requires PostgreSQL 9.1 or later. In older version you can subsitute:

... = substring(?, 9)

Because you want characters 9 and 10.


This should work, too:

Article.where("date_part('day', created_at::date)::int
                        = date_part('day', ?::date)", today)

Note, that you must cast '2012-01-16' to date, not to interval. '2012-01-16'::interval would be nonsense.

1
Szymon Lipiński On

According to the documentation there are two functions:

  • date_part(text, timestamp)
  • date_part(text, interval)

so database cannot choose which one you want. Cast the second parameter to timestamp, e.g. like this:

DATE_PART('day', created_at::interval) = DATE_PART('day', ?::interval)