Extract day of week from date field in PostgreSQL assuming weeks start on Monday
If you need the day of the week with Monday as 1, Tuesday as 2,..., Sunday as 7, you can use the EXTRACT(DOW)
function and make some fancy mod
magic in PostgreSQL:
This way you neatly bypass the default DOW
system, where Sunday is 0 and Monday is 1.
Adjusting weekdays to your needs
If your days of the week should start from 0 (Monday), you got it covered:
Here ISODOW
returns weekday numbers as 1 for Monday through 7 for Sunday. Subtracting 1 gives you a nice range of 0-6 starting with Monday.
Textual representation of weekdays
If you'd rather write out the weekdays, PostgreSQL provides the TO_CHAR()
function:
There are a bunch of formatting tokens, for example 'Day' for full name, 'Dy' for three letters, or simply 'D' for one letter.
Making weekdays dance to your tune
For custom weekday numbering, you can use some sweet CASE
statements:
This snippet will make Sunday dance as 6 and Monday groove as 0. Groovy, right?
Beyond simple extraction: More tricks up your sleeve
Days of the week for a range of dates
If you want to build a weekday table over a range of dates:
Filtering weekdays for business analysis
For a working week report, filtering for weekdays is as easy as pie:
Timezones, the spoilsports
For accurate extraction from dates, mind the timezones:
Be careful! Timezones can alter the perceived day of a datetime significantly.
Was this article helpful?