Sunday, December 22, 2024

MySQL DAYOFWEEK() Function

 The DAYOFWEEK() function in MySQL is used to return the day of the week for a given date. The result is an integer value where:

  • 1 represents Sunday
  • 2 represents Monday
  • 3 represents Tuesday
  • 4 represents Wednesday
  • 5 represents Thursday
  • 6 represents Friday
  • 7 represents Saturday

Syntax

DAYOFWEEK(date)
  • date: A valid date expression (e.g., 'YYYY-MM-DD', 'YYYY-MM-DD HH:MM:SS').

Example Usage

Example 1: Basic Usage

SELECT DAYOFWEEK('2024-12-23');

Output: 2 (Monday)

Example 2: Using with CURDATE()

SELECT DAYOFWEEK(CURDATE());

This will return the day of the week for the current date.

Example 3: Using in a Query

SELECT name, hire_date, DAYOFWEEK(hire_date) AS day_of_week
FROM employees;

This query retrieves the day of the week for each employee's hire date.

Notes

  • The numbering (Sunday as 1 to Saturday as 7) corresponds to the U.S. convention.
  • If you prefer a different starting day of the week, you can use other functions like WEEKDAY() (which starts with Monday as 0) or modify your query logic.

No comments:

Post a Comment