Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select day of week from date

Tags:

mysql

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).

like image 907
Kevin Avatar asked May 11 '11 16:05

Kevin


People also ask

Can Excel determine the day of the week from a date?

The Excel WEEKDAY function takes a date and returns a number between 1-7 representing the day of week. By default, WEEKDAY returns 1 for Sunday and 7 for Saturday, but this is configurable. You can use the WEEKDAY function inside other formulas to check the day of week.

How do you find the day of the week from a date?

For a Gregorian date, add 0 for 1900's, 6 for 2000's, 4 for 1700's, 2 for 1800's; for other years, add or subtract multiples of 400. For a Julian date, add 1 for 1700's, and 1 for every additional century you go back. Add the last two digits of the year. Divide by 7 and take the remainder.

How do I select a specific day of the week in SQL?

MySQL DAYOFWEEK() Function The DAYOFWEEK() function returns the weekday index for a given date (a number from 1 to 7). Note: 1=Sunday, 2=Monday, 3=Tuesday, 4=Wednesday, 5=Thursday, 6=Friday, 7=Saturday.

How do I select the day of the week in Excel?

On the right, click the “Type” box and enter “dddd” (without quotes) for full day names (like Monday) or “ddd” for shortened day names (like Mon). Then, at the bottom, click “OK.” Excel will turn your selected dates into days of the week. And that's how you know what day it was on a specific date in Microsoft Excel.


1 Answers

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.

like image 59
Henry Avatar answered Sep 20 '22 00:09

Henry