stack over
stack over

Reputation: 55

SQL setting ORDER BY

Is it possible to set the ORDER BY in a sql statement to the values you want? For example, if I want to choose the values for Day in this order: Thu, Sat, Sun, Mon

SELECT * 
FROM `NFL_Games` 
WHERE Week = '1' 
ORDER BY Day

Upvotes: 2

Views: 58

Answers (5)

jeschafe
jeschafe

Reputation: 2683

Something like this would work.. maybe a little annoying because of the case statement but would do the job.

SELECT *, 
       CASE fstrDay 
         WHEN 'Thursday' THEN 0 
         WHEN 'Friday' THEN 1 
         WHEN 'Saturday' THEN 2 
         WHEN 'Sunday' THEN 3 
         WHEN 'Monday' THEN 4 
         WHEN 'Tuesday' THEN 5 
         WHEN 'Wednesday' THEN 6 
       END AS flngOrder 
FROM   NFL_Games
WHERE  Week = '1'
ORDER  BY flngOrder ASC 

Upvotes: 0

Deepshikha
Deepshikha

Reputation: 10284

As Order by is the last clause that is processed while executing a query , yes if your select statement has day column ( either calculated based on date from table 'NFL_Games' or the table has a column 'Day' you can specify ordering among rows in your final set.

Upvotes: 0

Raphaël Althaus
Raphaël Althaus

Reputation: 60493

you can use a case when clause for personal orderings...

order by
(case Day
 when 'Thu' then 1
 when 'Sat' then 2
 when 'Sun' then 3
 when 'Mon' then 4
 else 5 end), 
 Day

Upvotes: 7

eulloa
eulloa

Reputation: 242

That seems perfectly legit; you can also sort by ascending or descending, depending on your preference.

Upvotes: -2

Nicolai
Nicolai

Reputation: 5787

Yes, you can use expressions in ORDER BY

SELECT * FROM `NFL_Games` WHERE Week = '1' ORDER BY DAYOFWEEK( date_field )

Upvotes: 0

Related Questions