Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to change the first day of the week in PostgreSQL

Tags:

postgresql

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. Please suggest solution for this.

like image 503
user3659532 Avatar asked Sep 14 '25 21:09

user3659532


1 Answers

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-18 20:38:40');

Returns 0, 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.

like image 124
khampson Avatar answered Sep 16 '25 19:09

khampson