SQLite automatically chooses the estimated optimal join order; the table order in the query has no effect.
There are two ways to optimize this query.
If the filter on uniqueidentifier2
removes most table1
records from the result, then it would be fastest to look up table2
records with matching uniqueidentifier2
values first, then to look up the corresponding table1
records, and then to sort the result.
This would require the following indexes:
CREATE INDEX t2_uid2_idx ON table2(uniqueidentifier2);
-- CREATE INDEX t1_pk ON table1(PK); -- primary keys have this automatically
If most table1
records will show up in the result, then it would be more efficient to go through table1
in the proper order and look up correspondig table2
records.
This would require the following indexes:
CREATE INDEX t1_vc1_idx ON table1(varchar1);
CREATE INDEX t2_FK_uid2_idx ON table2(FK, uniqueidentifier2);
(Having uniqueidentifier2
in the second index optimizes for this particular query, but might be not worth the storage and update overhead if you have many other queries.)
To check how queries are actually implemented, execute EXPLAIN QUERY PLAN.
SQLiteStudio sorts the database objects by type (table, index, trigger, view), but inside each group, sorts them randomly.
(If you consider this a bug, report it.)
The sqlite3
shell dumps tables in the order in which they are stored in the sqlite_master
table, which is typically the same order in which they were (re)created.
Best Answer
When there is an index, both queries just take the first entry from the index.
When there is no index, MIN() does a single pass through the table, and ORDER BY sorts only as much as is needed for the LIMIT, which ends up the same effort. (Older versions of SQLite did sort everything.)