How do I find the day of week of a date-time field? I'm trying to extract the the day of the week from a column in a sql query in postgres. While
SELECT EXTRACT(DOW FROM '2011-07-07')
works, the following query does not work and I can't figure it out:
SELECT EXTRACT(DOW FROM TIMESTAMP date) as day
FROM purchases GROUP BY day;
It's like postgres won't let me find the day of the week for fields but only constants. How do I find the day of week for a field?
Best Answer
The whole issue revolves around
CAST
ing and quirky PostgreSQL syntax.CAST
ing strings asDATE
s:It's very simple - your first line of code:
does not work. This is because, as far as PostreSQL is concerned, '2011-07-07' is just a string literal, not a
DATE
. This does work:Note the extra
DATE
thatCAST
s the string as such. You can alsoCAST
it this way:This double colon (::) is very much a PostreSQL thing. It's really quite "obvious", once you grasp the PostgreSQL syntax (it had me stumped for a couple of minutes!)
A date field:
So, we have a date field - with records as below:
So, to get the "day of week" from a date (note the two
FROM
s - doesn't work without theFROM
between brackets):Now, for a timestamp field:
And:
And DOW (again, note the two
FROM
s):Quirky syntax (the double colon also OK, if you want to be really explicit), but it works fine once you've mastered it.