Day of the week
How do I write a query that will tell me what day of the week a particular date is?

    Requires Free Membership to View

    By submitting your registration information to SearchOracle.com you agree to receive email communications from TechTarget and TechTarget partners. We encourage you to read our Privacy Policy which contains important disclosures about how we collect and use your registration and other information. If you reside outside of the United States, by submitting this registration information you consent to having your personal data transferred to and processed in the United States. Your use of SearchOracle.com is governed by our Terms of Use. You may contact us at webmaster@TechTarget.com.

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


This was first published in November 2002

Join the conversationComment

Share
Comments

    Results

    Contribute to the conversation

    All fields are required. Comments will appear at the bottom of the article.