Andrei Serdeliuc

My (s)crapbook

SQL ORDER By

Have you ever had the need to shoot yourself in the foot?

Here’s a neat way of doing just that, with SQL. If you ever need to manually specify the order in an ORDER BY statement, you can do it like so:

SELECT * FROM `table_name`
ORDER BY ( CASE
    WHEN order_column = 2 THEN 0
    WHEN order_column = 1 THEN 1
    WHEN order_column = 3 THEN 2
END )

Comments