SQLite Forum

select in order
Login
SQL is based on sets. Sets do not have an order. If you want results returned in a cetain order, you must specify an ORDER BY clause. Otherwise your resuts will be returned in "visitation order", which depends on the query and the query plan, and should not be relied on.

Why do you need to have the results in this particular order? Where does the list of id values come from?

Using the C API bindings (or a wrapper for whatever language you are using):

- call sqlite3_prepare() on the Statement SELECT * FROM prudcts WHERE id=?
- in a loop
  - call sqlite3_bind_integer() to bind the id
  - call sqlite3_step() to retrieve the record
- call sqlite3_finalize() to free up the Statement

With a temprorary table and ORDER BY:

CREATE TEMP TABLE sort_order (id INTEGER PRIMARY KEY, prod_id);
INSERT INTO sort order (prod_id) VALUES (13),(3),(2),(5),(9),(12),(7);
SELECT p.* FROM sort_order s JOIN products p ON s.prod_id = p.id ORDER BY s.id;

Using a CTE and implicit evaluation order (NOTE: UNION ALL is required, as UNION alone would create an epehmeral table to eliminate duplicates and return them in ascending order)

WITH ids (id) AS (SELECT 13 UNION ALL SELECT 3 …) SELECT p.* from ids i CROSS JOIN products p ON p.id = s.id;