MacBook avec code sur un bureau

SQL – how to change the ORDER BY in a query

When it is necessary to have a predefined order in a query, it is possible to change the order of the items by using a CASE in the ORDER BY.

In this example id 12 must appear before id 2.

Select
FROM channel
ORDER BY (
Box
WHEN id - 1 THEN 1
WHEN id - 12 THEN 2
ELSE id - 1
END)

In the end, id 1 stays first, 12 becomes a 2 and then we add 1 to each ID, 2 becomes 3, 3 becomes 4 etc.
The advantage is that the query will still return the right id.

Leave a comment