Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manual order in SQL

Tags:

sql

mysql

If I have a table of things...

ThingName | ThingCategory
-------------------------
thing 1   | cat1
thing 2   | cat2
thing 3   | cat3

How would I select them ordered by first cat2, then cat1, then cat3

Is this even possible?

like image 873
Undefined Avatar asked Oct 28 '25 14:10

Undefined


2 Answers

A switch in the order clause is one way to get you there with code alone:

select *
from Things
order by case
    when ThingCategory = 'cat2' then 1
    when ThingCategory = 'cat1' then 2
    when ThingCategory = 'cat3' then 3
    else 4 -- Might want the default case, too
end

However, this type of functionality is often better handled by data rather than code. As in, if you had a ThingCategories table, that table could have an Ordinal integer column. At that point, you can simply have the following query:

select t.*
from Things t
    join ThingCategories c on t.ThingCategory = c.ThingCategory
order by c.Ordinal

This way you won't have to maintain literals in code (good luck with that), and the users can change ordering by simply updating ordinals in a table (no need to bother you).

like image 122
Tim Lehner Avatar answered Oct 31 '25 05:10

Tim Lehner


You can do it like this

SELECT ThingName , ThingCategory
    FROM yourtabe
    ORDER BY 
     CASE
        WHEN ThingCategory = 'cat2' THEN 1
        WHEN ThingCategory = 'cat1' THEN 2
        WHEN ThingCategory = 'cat3' THEN 3
    END
like image 44
Marc Avatar answered Oct 31 '25 04:10

Marc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!