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
    by int(

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

Dig Deeper on Oracle and SQL

Start the conversation

Send me notifications when other members comment.

Please create a username to comment.