Hello guys I have a specific question about the AND clause in SQL.
The two following SQL statements provide the same output:
SELECT * FROM Table1 t1 INNER JOIN Table2 t2 ON t1.id = t2.id AND t2.id = 0
SELECT * FROM Table1 t1 INNER JOIN Table2 t2 ON t1.id = t2.id WHERE t2.id = 0
Notice the difference at the end of the query. In the first one, I use the AND clause (without using the WHERE clause before). In the second one, I use a WHERE to specify my id.
- Is the first syntax correct?
- If yes, is the first one better in terms of performance (not using WHERE clause for filtering after)?
- Should I expect different outputs with different queries?
Thanks for your help.
Yes, no, and no.
To be specific:
Yes, the syntax is correct. Conceptually, the first query creates an inner join between
t1andt2with the join conditiont1.id = t2.id AND t2.id = 0, while the second creates an inner join ont1.id = t2.idand then filters the result using the conditiont2.id = 0.However, no SQL engine I know of would actually execute either query like that. Rather, in both cases, the engine will optimize both of them to something like
t1.id = 0 AND t2.id = 0and then do two single-row lookups.No, pretty much any reasonable SQL engine should treat these two queries as effectively identical.
No, see above.
By the way, the following ways to write the same query are also valid: