sqlite query unsorted result sqlite query unsorted result sqlite sqlite

sqlite query unsorted result


Without an order by clause, there's no guarantee on the order a database returns the results to you. SQLite, unfortunately, doesn't have something like MySQL's field for custom sorting, but you can jimmy-rig something with a case expression:

SELECT   id, nameFROM     master_movievod WHERE    id IN (31165, 31160, 31321, 31322, 31199, 31136)ORDER BY CASE ID WHEN 31165 THEN 0                 WHEN 31160 THEN 1                 WHEN 31321 THEN 2                 WHEN 31322 THEN 3                 WHEN 31199 THEN 4                 WHEN 31136 THEN 5          END ASC


Unfortunately, SQLite does not have an option like MySQL's FIELD for doing a custom ordering. You are left with two options. The first is that you could create a custom table containing the ordering you want and use that to sort. This option isn't very attractive. The second (and easier) option is to use ORDER BY CASE to achieve the order you want:

SELECT id, name FROM master_movievodWHERE id IN (31165,31160,31321,31322,31199,31136)ORDER BY     CASE id        WHEN 31165 THEN 0        WHEN 31160 THEN 1        WHEN 31321 THEN 2        WHEN 31322 THEN 3        WHEN 31199 THEN 4        WHEN 31136 THEN 5    END ASC