Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract day of week from date field in PostgreSQL assuming weeks start on Monday

select extract(dow from datefield) 

extract a number from 0 to 6, where 0 is Sunday; is there a way to get the day of the week in SQL assuming that weeks start on Monday (so 0 will be Monday)?

like image 882
Eugenio Avatar asked Dec 16 '16 10:12

Eugenio


People also ask

How do you get the day of the week from a date in PostgreSQL?

In PostgreSQL you can use the extract() function to get the day from a date. You can also use date_part() to do the same thing. When extracting the day from a date, you need to specify what sense of the word “day” you mean. For example, “day of week”, “day of month”, “day of year”, etc.

How do I get the day of the week from a timestamp in SQL?

MySQL DAYOFWEEK() Function The DAYOFWEEK() function returns the weekday index for a given date (a number from 1 to 7). Note: 1=Sunday, 2=Monday, 3=Tuesday, 4=Wednesday, 5=Thursday, 6=Friday, 7=Saturday.

How do I extract the day of the week in PostgreSQL?

In PostgreSQL you can use the extract () function to get the day from a date. You can also use date_part () to do the same thing. When extracting the day from a date, you need to specify what sense of the word “day” you mean. For example, “day of week”, “day of month”, “day of year”, etc.

How do you extract the day from a date?

When extracting the day from a date, you need to specify what sense of the word “day” you mean. For example, “day of week”, “day of month”, “day of year”, etc.

How do you calculate partial months in PostgreSQL?

PostgreSQL 's approach uses the month from the earlier of the two dates when calculating partial months. For example, age ('2004-06-01', '2004-04-30') uses April to yield 1 mon 1 day, while using May would yield 1 mon 2 days because May has 31 days, while April has only 30. Subtraction of dates and timestamps can also be complex.

How to extract day of week from timestamps in Excel?

Create the column which extracts day of week from timestamp column Within the Extract keyword we have to mention DOW as we are getting day of week from timestamp


2 Answers

From the manual

isodow      The day of the week as Monday (1) to Sunday (7) 

So, you just need to subtract 1 from that result:

psql (9.6.1) Type "help" for help.  postgres=> select extract(isodow from date '2016-12-12') - 1;   ?column? -----------          0 (1 row) postgres=> 
like image 158
a_horse_with_no_name Avatar answered Oct 22 '22 13:10

a_horse_with_no_name


Use date_part Function dow()

Here 0=Sunday, 1=Monday, 2=Tuesday, ... 6=Saturday

   select extract(dow from date '2016-12-18'); /* sunday */ 

Output : 0

    select extract(isodow from date '2016-12-12'); /* Monday  */ 

Ouput : 1

like image 35
Mr. Bhosale Avatar answered Oct 22 '22 13:10

Mr. Bhosale