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.

Publicités

In this example id 12 must appear before the 2.

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

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

Publicités

Leave a Reply