Ravi Chandra
Ravi Chandra

Reputation: 687

Execution sequence of IN and JOIN in MySQL

I have a SQL query which looks like the following.

SELECT A.a, count(B.id)
FROM TableA A inner join TableA B on A.referId = B.id
WHERE A.id in (123,2424,232...)
GROUP BY A.id

While executing this query

  1. The rows are filtered using where clause first and then join is performed or
  2. First join is performed, then the rows are filtered?

I am running this query on MySQL Server. Assuming TableA contains million rows. Is there any alternative and efficient way of writing this query?

Upvotes: 2

Views: 393

Answers (2)

Sharvari
Sharvari

Reputation: 41

The rows selected by a query are filtered first by the FROM clause join conditions, then the WHERE clause search conditions, and then the HAVING clause search conditions. Inner joins can be specified in either the FROM or WHERE clause without affecting the final result.

Upvotes: 0

O. Jones
O. Jones

Reputation: 108839

The order of execution is determined by the query planner.

You can influence it by creating indexes.

For this query I suggest changing COUNT(b.ID) to COUNT(*). I also suggest creating a compound index on (id, referId). That should provide coverage for the stuff you need from the first instance of your table.

For more information on query performance, this is an excellent resource. http://planet.mysql.com/entry/?id=661727

Upvotes: 1

Related Questions