Ask the Expert

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

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

There are Comments. Add yours.

 
TIP: Want to include a code block in your comment? Use <pre> or <code> tags around the desired text. Ex: <code>insert code</code>

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy
Sort by: OldestNewest

Forgot Password?

No problem! Submit your e-mail address below. We'll send you an email containing your password.

Your password has been sent to: