Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using limit in sqlite SQL statement in combination with order by clause

Tags:

sql

sqlite

Will the following two SQL statements always produce the same result set?

 1. SELECT * FROM MyTable where Status='0' order by StartTime asc limit 10

 2. SELECT * FROM (SELECT * FROM MyTable where Status='0' order by StartTime asc) limit 10
like image 221
nabulke Avatar asked May 03 '12 10:05

nabulke


People also ask

Can we use limit after ORDER BY?

Yes, it's after the ORDER BY.

Does SQLite support limit?

Maximum Database SizeThe maximum size of a database file is 4294967294 pages. At the maximum page size of 65536 bytes, this translates into a maximum database size of approximately 1.4e+14 bytes (281 terabytes, or 256 tebibytes, or 281474 gigabytes or 256,000 gibibytes).

How do we limit which rows are returned by a query?

The SQL LIMIT clause restricts how many rows are returned from a query. The syntax for the LIMIT clause is: SELECT * FROM table LIMIT X;. X represents how many records you want to retrieve. For example, you can use the LIMIT clause to retrieve the top five players on a leaderboard.

When sorting query results from a table what is the sort limit?

In fact, sorting will stop as soon as first 20 sorted results are found.


1 Answers

No. First because the StartTime column may not have UNIQUE constraint. So, even the first query may not always produce the same result - with itself!

Second, even if there are never two rows with same StartTime, the answer is still negative.

The first statement will always order on StartTime and produce the first 10 rows. The second query may produce the same result set but only with a primitive optimizer that doesn't understand that the ORDER BY in the subquery is redundant. And only if the execution plan includes this ordering phase.

The SQLite query optimizer may (at the moment) not be very bright and do just that (no idea really, we'll have to check the source code of SQLite*). So, it may appear that the two queries are producing identical results all the time. Still, it's not a good idea to count on it. You never know what changes will be made in a future version of SQLite.

I think it's not good practice to use LIMIT without ORDER BY, in any DBMS. It may work now, but you never know how long these queries will be used by the application. And you may not be around when SQLite is upgraded or the DBMS is changed.

(*) @Gareth's link provides the execution plan which suggests that current SQLite code is dumb enough to execute the redundant ordering.

like image 192
ypercubeᵀᴹ Avatar answered Sep 18 '22 01:09

ypercubeᵀᴹ