Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happend first in mysql: join or where

Tags:

sql

mysql

Let's say I have two tables A and B and the following query:

select *
from A
inner join B on A.id = B.id
Where A.id = 5

Does mysql first performs the join or the where?

Edit:

Cause if for example A contains 1000 rows, after the where condition it'll contain only 1 row. Performing join on a 1 row table is much more efficient so it seems like performing the where first and only then the join is more efficient.

like image 600
julius_am Avatar asked Dec 31 '13 07:12

julius_am


People also ask

Which comes first WHERE or join?

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.

Does WHERE come before or after join in SQL?

If you move the same filter to the WHERE clause, you will notice that the filter happens after the tables are joined.

Does WHERE come before inner join?

The where clause will be executed before the join so that it doesn't join unnecessary records.

Can we use join after WHERE clause?

To use the WHERE clause to perform the same join as you perform using the INNER JOIN syntax, enter both the join condition and the additional selection condition in the WHERE clause. The tables to be joined are listed in the FROM clause, separated by commas. This query returns the same output as the previous example.


1 Answers

The join happens before the where, however...

The where clause is a filter for all rows returned by the join, but the optimizer will recognise that if an index exists on A.id, it will be used to retrieve rows from A that match, then the join will happen, then theoretically the where clause will filter the results, but again the optimizer will recognise that the condition will already be met so it will skip it as a filter.

All that said, the optimizer will always return the same result as would be returned without the optimizer.

like image 106
Bohemian Avatar answered Sep 23 '22 12:09

Bohemian