Tuesday, December 24, 2024

MySQL WEEKDAY() Function

 The WEEKDAY() function in MySQL is used to return the weekday index for a given date. It returns an integer value ranging from 0 (Monday) to 6 (Sunday).

Syntax

WEEKDAY(date)

Parameters

  • date: The date for which you want to determine the weekday. This can be a DATE, DATETIME, or a string in a valid date format.

Return Values

  • The function returns an integer:
    • 0 for Monday
    • 1 for Tuesday
    • ...
    • 6 for Sunday

Examples

Example 1: Basic Usage

SELECT WEEKDAY('2024-12-24') AS WeekdayIndex;

Output:
0 (Monday)

Example 2: Current Date

SELECT WEEKDAY(CURDATE()) AS WeekdayIndex;

This returns the weekday index for the current date.

Example 3: Using in a WHERE Clause

SELECT * 
FROM events
WHERE WEEKDAY(event_date) = 5;

This selects all rows where the event date falls on a Saturday.

Notes

  • If you need the weekday name (e.g., 'Monday', 'Tuesday'), you can use the DAYNAME() function instead.
  • The WEEKDAY() function starts with Monday as 0, which differs from some other MySQL functions like DAYOFWEEK(), where Sunday is 1.

No comments:

Post a Comment