How does 'LIMIT' parameter work in sql?
From MySQL Reference Manual:
If you use LIMIT row_count with ORDER BY, MySQL ends the sorting as soon as it has found the first row_count rows of the sorted result, rather than sorting the entire result. If ordering is done by using an index, this is very fast. If a filesort must be done, all rows that match the query without the LIMIT clause must be selected, and most or all of them must be sorted, before it can be ascertained that the first row_count rows have been found. In either case, after the initial rows have been found, there is no need to sort any remainder of the result set, and MySQL does not do so.
So it looks like it's possible that the entire result set is known before the LIMIT
is applied. But MySQL will try everything it can not to do so. And you can help it by providing useful indexes that match your queries.
EDIT: Furthermore, if the set is not sorted it terminates the SELECT
operation as soon as it's streamed enough rows to the result set.
SELECT * FROM your_table
LIMIT 0, 10
This will display the first 10 results from the database.
SELECT * FROM your_table
LIMIT 5, 5
This will show records 6, 7, 8, 9, and 10
It's like telling MySql;
I want you to start counting from 5+1 or the 6th record, but Select only upto 5 records