Q
Problem solve Get help with specific problems with your technologies, process and projects.

Sorting by day name

I have this table:

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


This was last published in June 2004

Dig Deeper on Oracle and SQL

PRO+

Content

Find more PRO+ content and other member only offers, here.

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.

Start the conversation

Send me notifications when other members comment.

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

Please create a username to comment.

-ADS BY GOOGLE

SearchDataManagement

SearchBusinessAnalytics

SearchSAP

SearchSQLServer

TheServerSide

SearchDataCenter

SearchContentManagement

SearchFinancialApplications

Close