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.


    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.

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 first published in June 2004

Join the conversationComment

Share
Comments

    Results

    Contribute to the conversation

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