Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order of execution of ORDER BY and LIMIT in a MySQL query

I have a query like this where I want to display sorted records in a paginated format.

This is my query.

SELECT * FROM answers
WHERE userid = '10'
ORDER BY votes LIMIT 10, 20

The two arguments to LIMIT will be used for generating page-by-page display of records. Now, my problem is ORDER BY. How does MySQL execute this query?

1st way

  • Select the records according to filters
  • Sort them
  • Limit them

2nd way

  • Select the records according to filters
  • Limit them
  • Sort them

If I think like MySQL engine, I would want to implement 2nd, since I would then have to sort lesser records?

Can somebody throw some light on this?

Regards

like image 522
vikmalhotra Avatar asked Oct 13 '10 03:10

vikmalhotra


People also ask

Which comes first ORDER BY or limit?

The ORDER BY clause goes after the FROM clause but before the LIMIT .

Does MySQL allow the use of ORDER BY and limit in the same query?

In MySQL, the LIMIT clause is used with the SELECT statement to restrict the number of rows in the result set. The Limit Clause accepts one or two arguments that are offset and count. The value of both the parameters can be zero or positive integers.

What is the correct order of SQL query execution?

Six Operations to Order: SELECT, FROM, WHERE, GROUP BY, HAVING, and ORDER BY. By using examples, we will explain the execution order of the six most common operations or pieces in an SQL query. Because the database executes query components in a specific order, it's helpful for the developer to know this order.


1 Answers

A SQL LIMIT will in all databases always work on the result of a query, so it will run the query with the ORDER BY and that result will then be limited. This is a functional requirement, the database not perse needs to execute it like that.

Thus the 1st way.

like image 55
Kdeveloper Avatar answered Sep 20 '22 20:09

Kdeveloper