Skip to content
Advertisement

Maintain order when using SQLite WHERE-clause and IN operator

Consider the following tbl:

For reference, tbl looks like this:

When issuing the following statement, the result will be ordered according to ID.

However, I need the ordering to adhere to the order of the passed list of values. Here’s what I am looking for:

Advertisement

Answer

You can create a CTE that returns 2 columns: the values that you search for and for each value the sort order and join it to the table.
In the ORDER BY clause use the sort order column to sort the results:

See the demo.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement