Skip to content
Advertisement

Maintain order when using SQLite WHERE-clause and IN operator

Consider the following tbl:

CREATE TABLE tbl (ID INTEGER, ticker TEXT, desc TEXT);

INSERT INTO tbl (ID, ticker, desc) 
    VALUES (1, 'GDBR30', '30YR'),
           (2, 'GDBR10', '10YR'),
           (3, 'GDBR5', '5YR'),
           (4, 'GDBR2', '2YR');

For reference, tbl looks like this:

ID   ticker   desc
1    GDBR30   30YR
2    GDBR10   10YR
3    GDBR5    5YR
4    GDBR2    2YR

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

SELECT * FROM tbl
WHERE ticker in ('GDBR10', 'GDBR5', 'GDBR30')

ID   ticker   desc
1    GDBR30   30YR
2    GDBR10   10YR
3    GDBR5    5YR

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

ID   ticker   desc
2    GDBR10   10YR
3    GDBR5    5YR
1    GDBR30   30YR

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:

WITH cte(id, ticker) AS (VALUES (1, 'GDBR10'), (2, 'GDBR5'), (3, 'GDBR30'))
SELECT t.* 
FROM tbl t INNER JOIN cte c
ON c.ticker = t.ticker
ORDER BY c.id

See the demo.

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