I have this table:
By submitting your personal information, you agree that TechTarget and its partners may contact you regarding relevant content, products and special offers.
Name Dayname xxxx Mon xxxx Wed xxxx Thu
Both columns are of String type. I need a query to select a list of data from the Name column in order by Dayname. The problem is, Dayname is string type. If I do select * from mytable order by dayname the order result would be Mon, Thu, Wed... What I need is Mon, Wed, Thu...
I have tried select * from mytable order by DAYWEEK(Dayname) but it failed. By the way, this is an MS Access database.
You might want to design your table with day numbers instead of day names. However, while numbers would sort properly, you would then need to translate them into day names for display purposes. So it's kind of a "six of one, half dozen of t'other" situation.
Let's translate your day names right in the ORDER BY clause:
select Name , Dayname from yourtable order by int( instr('SunMonTueWedThuFriSat' ,Dayname)/3 )+1
The way this works is by using the INSTR function to find the position of the Dayname value within the string 'SunMonTueWedThuFriSat'. This will be the starting position of the Dayname, i.e. 1, 4, 7, 10, 13, 16, or 19. Divide by 3, throw away the remainder using the INT function, and add 1. Voilà.
Actually, for sorting purposes, you only need the the position from the INSTR function. The rest of the expression merely turns the position into a day number between 1=Sun and 7=Sat. Copy the full expression into the SELECT if you need to return the day number.
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, SQL Server, DB2, object-oriented and data warehousing gurus are waiting to answer your toughest questions.
Dig Deeper on Oracle and SQL
Have a question for an expert?
Please add a title for your question
Get answers from a TechTarget expert on whatever's puzzling you.