Q

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


This was first published in November 2002

Dig deeper on Oracle and SQL

Pro+

Features

Enjoy the benefits of Pro+ membership, learn more and join.

Have a question for an expert?

Please add a title for your question

Get answers from a TechTarget expert on whatever's puzzling you.

You will be able to add details on the next page.

0 comments

Oldest 

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:

SearchDataManagement

SearchBusinessAnalytics

SearchSAP

SearchSQLServer

TheServerSide

SearchDataCenter

SearchContentManagement

SearchFinancialApplications

Close