Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WHERE clause before INNER JOIN

If I have

SELECT * FROM Table1 t1  LEFT JOIN Table2 t2 ON t1.id = t2.id  WHERE t1.user='bob'; 

Does the WHERE clause run after the two tables are JOINED?

How do I make it so it runs prior to the JOIN?

like image 894
user1124535 Avatar asked Apr 12 '12 23:04

user1124535


People also ask

Can I use WHERE before inner join?

The where clause will be executed before the join so that it doesn't join unnecessary records. So your code is fine the way it is.

Which performs first WHERE clause or join clause?

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.

What clause has to be used before the inner join keyword?

Inner Join syntax basically compares rows of Table1 with Table2 to check if anything matches based on the condition provided in the ON clause. When the Join condition is met, it returns matched rows in both tables with the selected columns in the SELECT clause.

Can we use joins in WHERE clause?

You join two tables by creating a relationship in the WHERE clause between at least one column from one table and at least one column from another. The join creates a temporary composite table where each pair of rows (one from each table) that satisfies the join condition is linked to form a single row.


2 Answers

The where clause will be executed before the join so that it doesn't join unnecessary records. So your code is fine the way it is.

like image 61
Mosty Mostacho Avatar answered Oct 06 '22 17:10

Mosty Mostacho


Change the WHERE to another JOIN condition

LEFT JOIN Table2 t2 on t1.id = t2.id AND t1.user='bob'

like image 42
hkf Avatar answered Oct 06 '22 15:10

hkf