MySQL - DAYOFWEEK() Function



The MySQL DAYOFWEEK() function is used to retrieve the index of the weekday of the given date. This function returns a numerical value which can be either one of the following: 1 for Sunday, 2 for Monday, 3 for Tuesday, 4 for Wednesday, 5 for Thursday, 6 for Friday, 7 for Saturday respectively (as any week starts from Sunday).

Syntax

Following is the syntax of MySQL DAYOFWEEK() function −

DAYOFWEEK(date);

Parameters

This method accepts the date value from which you need to extract the day of the week (index) as a parameter.

Return value

This function returns the index of the weekday of the given date.

Example

In the following example, we are using the MySQL DAYOFWEEK() function to retrieve the name of a week day −

SELECT DAYOFWEEK('2019-05-25') As Result;

Output

The output for the query above is produced as given below −

Result
7

Example

If the day part in the given date is 0 this function returns NULL

SELECT DAYOFWEEK('2017-00-00') As Result;

Output

Following is the output −

Result
NULL

Example

If we pass an empty string or a non-string value as an argument to this function returns NULL.

SELECT DAYOFWEEK('') As Result;

Following is the output −

Result
NULL

Here, we are passing a non-string value as an argument to this function −

SELECT DAYOFWEEK(1990-11-11);

Following is the output −

Result
NULL

Example

In the following example, we are retrieving weekday index from the current date −

SELECT DAYOFWEEK(CURDATE());

Output

This will produce the following result −

Result
NULL

Example

We can also pass the column name as an argument to this function. Let us create a table named ORDERS using CREATE statement as shown below −

CREATE TABLE ORDERS (
   OID INT NOT NULL,
   DATE VARCHAR (20) NOT NULL,
   CUSTOMER_ID INT NOT NULL,
   AMOUNT DECIMAL (18, 2)
);

Now, insert the following records into the ORDERS table using the INSERT statement −

INSERT INTO ORDERS VALUES 
(102, '2009-10-08 00:00:00', 3, 3000.00),
(100, '2009-10-08 00:00:00', 3, 1500.00),
(101, '2009-11-20 00:00:00', 2, 1560.00),
(103, '2008-05-20 00:00:00', 4, 2060.00);

Execute the below query to fetch all the inserted records in the above-created table −

Select * From ORDERS;

Following is the ORDERS table −

OID DATE CUSTOMER_ID AMOUNT
102 2009-10-08 00:00:00 3 3000.00
100 2009-10-08 00:00:00 3 1500.00
101 2009-11-20 00:00:00 2 1560.00
103 2008-05-20 00:00:00 4 2060.00

Now, we use the MySQL DAYOFWEEK() function to fetch the corresponding day of the week for each order from the "ORDERS" table.

Select OID, DATE, DAYOFWEEK(DATE) As Result From ORDERS;

Output

The output is displayed as follows −

OID DATE Result
102 2009-10-08 00:00:00 5
100 2009-10-08 00:00:00 5
101 2009-11-20 00:00:00 6
103 2008-05-20 00:00:00 3
Advertisements