27

I have the following table in MySQL that records event counts of stuff happening each day

event_date     event_count
2011-05-03     21
2011-05-04     12
2011-05-05     12

I want to be able to query this efficiently by date range AND by day of week. For example - "What is the event_count on Tuesdays in May?"

Currently the event_date field is a date type. Are there any functions in MySQL that let me query this column by day of week, or should I add another column to the table to store the day of week?

The table will hold hundreds of thousands of rows, so given a choice I'll choose the most efficient solution (as opposed to most simple).

1
  • 1
    Thanks for your well-written question. Just an FYI - greetings and title tags are frowned upon on SO, as it's not a forum. Hope you find the answer you're looking for. Commented May 11, 2011 at 16:27

3 Answers 3

59

Use DAYOFWEEK in your query, something like:

SELECT * FROM mytable WHERE MONTH(event_date) = 5 AND DAYOFWEEK(event_date) = 7;

This will find all info for Saturdays in May.

To get the fastest reads store a denormalized field that is the day of the week (and whatever else you need). That way you can index columns and avoid full table scans.

Just try the above first to see if it suits your needs and if it doesn't, add some extra columns and store the data on write. Just watch out for update anomalies (make sure you update the day_of_week column if you change event_date).

Note that the denormalized fields will increase the time taken to do writes, increase calculations on write, and take up more space. Make sure you really need the benefit and can measure that it helps you.

2
  • For those on 2012, DAYOFWEEK is not recognized after 2008. For 2012 use DAY instead. Great response, just wanted to make note for others looking how to do this on newer versions of SQL Server. Commented May 20, 2016 at 12:28
  • @JeremyDodt DAY seems to be a synonym of DAYOFMONTH, not DAYOFWEEK dev.mysql.com/doc/refman/8.2/en/…
    – CalvT
    Commented Jan 2 at 12:56
4

Check DAYOFWEEK() function

4

If you want textual representation of day of week - use DAYNAME() function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.