Index: src/where.c ================================================================== --- src/where.c +++ src/where.c @@ -4054,11 +4054,15 @@ if( aSortCost[isOrdered]==0 ){ aSortCost[isOrdered] = whereSortingCost( pWInfo, nRowEst, nOrderBy, isOrdered ); } - rCost = sqlite3LogEstAdd(rUnsorted, aSortCost[isOrdered]); + /* TUNING: Add a small extra penalty (5) to sorting as an + ** extra encouragment to the query planner to select a plan + ** where the rows emerge in the correct order without any sorting + ** required. */ + rCost = sqlite3LogEstAdd(rUnsorted, aSortCost[isOrdered]) + 5; WHERETRACE(0x002, ("---- sort cost=%-3d (%d/%d) increases cost %3d to %-3d\n", aSortCost[isOrdered], (nOrderBy-isOrdered), nOrderBy, rUnsorted, rCost)); Index: test/orderby5.test ================================================================== --- test/orderby5.test +++ test/orderby5.test @@ -81,11 +81,11 @@ SELECT * FROM t2 WHERE a=0 ORDER BY a, b, c; } {~/B-TREE/} do_execsql_test 2.1b { EXPLAIN QUERY PLAN - SELECT * FROM t1 WHERE likelihood(a=0, 0.05) ORDER BY a, b, c; + SELECT * FROM t1 WHERE likelihood(a=0, 0.03) ORDER BY a, b, c; } {/B-TREE/} do_execsql_test 2.2 { EXPLAIN QUERY PLAN SELECT * FROM t1 WHERE +a=0 ORDER BY a, b, c; Index: test/where.test ================================================================== --- test/where.test +++ test/where.test @@ -580,11 +580,11 @@ } {/1 100 4 2 99 9 3 98 16 .* nosort/} do_test where-6.7.2 { cksort { SELECT * FROM t3 WHERE b>0 ORDER BY a LIMIT 1 } -} {1 100 4 sort} +} {1 100 4 nosort} ifcapable subquery { do_test where-6.8a { cksort { SELECT * FROM t3 WHERE a IN (3,5,7,1,9,4,2) ORDER BY a LIMIT 3 }