I need to change the week start date from Monday to Saturday in PostgreSQL. I have tried SET DATEFIRST 6;
but it doesn\'t work in PostgreSQL. Plea
You can just add +x, where x is the offset between postgres dow and what you want to achieve.
For example:
You want Sunday to be the first day of the week. 2018-06-03 is a Sunday and you want to extract the dow of it:
SELECT EXTRACT(DOW FROM DATE '2018-06-03')+1;
returns 1
That is probably the reason why postgres dow yields 0 for Sunday. Would it be 7, then
SELECT EXTRACT(DOW FROM DATE '2018-06-03')+1;
would return 8
.
It appears that DATEFIRST
is a thing in Microsoft Transact-SQL.
I don't believe Postgres has any exact equivalent, but you should be able to approximate it.
Postgres supports extracting various parts of a TIMESTAMP
via the EXTRACT
function. For your purposes, you would want to use either DOW
or ISODOW
.
DOW
numbers Sunday (0) through Saturday (6), while ISODOW
, which adheres to the ISO 8601 standard, numbers Monday (1) through Sunday (7).
From the Postgres doc:
This:
SELECT EXTRACT(DOW FROM TIMESTAMP '2001-02-16 20:38:40');
Returns 5
, while this:
SELECT EXTRACT(ISODOW FROM TIMESTAMP '2001-02-18 20:38:40');
Returns 7
.
So you would use a version of EXTRACT
in your queries to get the day of the week number. If you're going to use it in many queries, I would recommend creating a function which would centralize the query in one spot, and return the number transposed as you would like such that it started on Saturday (the transposition would vary depending on which numbering method you used in EXTRACT
). Then you could simply call that function in any SELECT
and it would return the transposed number.