MySQL – Does Join Occur Before LIMIT?

database-designMySQL

Imagine that I want to populate the last 10 questions of stackoverflow. I have a table that keep the questions list, a table to keep the question info, a table to list question's asker.

Now imagine that I want to get the last ten questions, so I have to join some tables and get the last items by ORDER BY ... DESC LIMIT 0 , 10. This gets me the last ten questions without any problems, but I think that there may be one issue.

MySQL may be first joining all tables and then pick the last ten items, so if I have to join 1 million rows to 1 million rows, it gets really bad performance.

I want to know if MySQL does do this, and if yes, how can I go around this issue?.

Best Answer

The only way around it is to refactor the query so as to alter the order of the EXPLAIN plan.

EXAMPLE : On May 16, 2011, I once answered a very rough question on StackOverflow

Fetching a Single Row from Join Table

Basically, you have to construct the query so that JOIN clauses are done last. Consequently, this implies that you must get the LIMIT executed beforehand.