MySQL numeric functions
MySQL string functions
MySQL Date/Time functions
MySQL aggregate functions
MySQL flow control functions
The DAYOFWEEK()
function in MySQL is used to get the day of the week for a given date. The returned day of the week is a number from 1 to 7, where 1 represents Sunday and 7 represents Saturday.
The syntax for DAYOFWEEK()
is:
DAYOFWEEK(date)
Where date
is a date or datetime expression from which the day of the week will be returned.
Here's an example of using DAYOFWEEK()
:
SELECT DAYOFWEEK('2023-05-11');
This will return '5', because May 11, 2023, falls on a Thursday, and Thursday is the fifth day of the week starting from Sunday.
You can also use DAYOFWEEK()
with columns in a table. For example, if you have a table named 'events' with a column 'event_date', you can get the day of the week for each event like this:
SELECT event_id, DAYOFWEEK(event_date) AS day_of_week FROM events;
This would return a result with the event ID and the day of the week for each event.
Note that the DAYOFWEEK()
function uses the ODBC standard, which considers Sunday as the first day of the week. If you want to use the ISO standard, where Monday is the first day of the week, you can use the WEEKDAY()
function instead. However, WEEKDAY()
returns values from 0 (Monday) to 6 (Sunday).
MySQL DAYOFWEEK Function Example:
DAYOFWEEK
function returns the index of the weekday (1 = Sunday, 2 = Monday, ..., 7 = Saturday).-- Example of using DAYOFWEEK SELECT DAYOFWEEK('2023-01-15') AS day_of_week_index;
Get Week Index from Date in MySQL:
DAYOFWEEK
.-- Example getting week index from date SELECT WEEK('2023-01-15') AS week_index;
Examples of Using DAYOFWEEK in MySQL Queries:
DAYOFWEEK
in queries to filter or analyze data based on weekdays.-- Example using DAYOFWEEK in WHERE clause SELECT * FROM events WHERE DAYOFWEEK(event_date) = 2; -- Selecting Monday events