Day of the week
How do I write a query that will tell me what day of the week a particular date is?
There are really only two choices: use whatever built-in database function is provided by your database system, or do the math yourself.
Most database systems have comprehensive date functions, and "day of the week" is usually included. Using Microsoft Access, for example, you can use the WEEKDAY(date) function, and the result will be an integer between 1 and 7, where 1=Sunday and 7=Saturday. Microsoft SQL Server's DATEPART(dw,date) function produces the same result. In Oracle, you use the TO_CHAR(date,'D') function. Each of these database systems has a mechanism whereby you can adjust which day of the week is associated with the number 1. MySQL, just to be different, gives you two functions: DAYOFWEEK(date) returns 1=Sunday through 7=Saturday, while WEEKDAY(date) returns 0=Monday through 6=Sunday.
If your database system does not include a "day of week" function -- and I cannot think of any that don't -- you can still do the math yourself, although doing it in one SQL query will be very, very tricky. See Eric Weisstein's Weekday for examples of algorithms you can use.
Finally, if you're interested, there's an algorithm that let's you calculate the day of the week for any date in your head. It's called the Doomsday Algorithm, and it was created by John Horton Conway, an eminent mathematician, perhaps best known as the inventor of the Game of Life.
For More Information
- Dozens more answers to tough SQL questions from Rudy Limeback.
- The Best SQL Web Links: tips, tutorials, scripts, and more.
- Have an SQL tip to offer your fellow DBAs and developers? The best tips submitted will receive a cool prize. Submit your tip today!
- Ask your technical SQL questions -- or help out your peers by answering them -- in our live discussion forums.
- Ask the Experts yourself: Our SQL, database design, Oracle, SQL Server, DB2, metadata, object-oriented and data warehousing gurus are waiting to answer your toughest questions.