MySQL - WEEKDAY() Function



The MYSQL WEEKDAY() function is used to retrieve the index of the weekday of the given date. This function returns a numerical value which can be one of the following −

  • 0 for Monday,

  • 1 for Tuesday,

  • 2 for Wednesday,

  • 3 for Thursday,

  • 4 for Friday,

  • 5 for Saturday and

  • 6 for Sunday

The WEEKDAY() function returns a NULL value if the argument passed to it is a NULL value.

Syntax

Following is the syntax of MySQL WEEKDAY() function −

WEEKDAY(date);

Parameters

This method accepts the date for which you want to find the weekday index as a parameter.

Return value

This function returns an index representing the day of the week for the specified date. The index is an integer ranging from 0 to 6.

Example

In the following example, we are using the MySQL WEEKDAY() function to fetch the index of the weekday of the given date −

SELECT WEEKDAY('2023-11-14') As Result;

Output

This will produce the following result −

Result
1

Example

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

SELECT WEEKDAY('2023-00-00') As Result;

Following is the output −

Result
NULL

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

SELECT WEEKDAY('') As Result;

Following is the output −

Result
NULL

Here, we are passing a non-string value as an argument. Thus, it returns NULL as result −

SELECT WEEKDAY(1990-11-11) As Result;

Following is the output −

Result
NULL

Example

Here, we are retrieving the weekday number of the current date (2023-11-20) −

SELECT WEEKDAY(CURDATE()) As Result;

Output

Following is the output −

Result
0

Example

In the following example, let us create a table named ORDERS using CREATE TABLE statement −

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 retrieve 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 WEEKDAY() function to calculate the weekday index number for each date value in the "DATE" column.

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

Output

The output is displayed as follows −

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