Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are all these SQL joins logically equivalent?

Tags:

sql

join

I'm just wondering if all of the following joins are logically equivalent, and if not, why not?

SELECT t1.x, t2.y from t1, t2 where t1.a=t2.a and t1.b=t2.b and t1.c = t2.c;

SELECT t1.x, t2.y from t1 join t2 on t1.a=t2.a where t1.b=t2.b and t1.c = t2.c;

SELECT t1.x, t2.y from t1 join t2 on t1.a=t2.a and t1.b=t2.b where t1.c = t2.c;

SELECT t1.x, t2.y from t1 join t2 on t1.a=t2.a and t1.b=t2.b and t1.c = t2.c;

I guess my real question is: does combining "where" with "on" doing something different from just having multiple conditions ANDed together with "on"?

I work with MySQL, in case that makes a difference.

like image 390
Ben Avatar asked Feb 23 '09 17:02

Ben


People also ask

What are logical joins in SQL Server?

physical joins are exactly like the joins you would create using SQL. These are passed to the database. Logical joins tell the repository how to group the tables to answer your query. Using multiple logical table sources it is possible to have many physical joins to one logical join (1:M).

What are the 4 types of joins in SQL?

Four types of joins: left, right, inner, and outer.

Which of the following is true about SQL joins?

Q 30 - Which of the following is true about SQL joins? A - The join condition is not separated from other search conditions in a query. B - The ON clause makes code difficult to understand. C - The join condition for natural join is basically an equijoin of all columns with same name.

Are Natural join and inner join same?

Natural Join joins two tables based on same attribute name and datatypes. Inner Join joins two table on the basis of the column which is explicitly specified in the ON clause.


1 Answers

They are logically equivalent and should produce the same result. However, the last one is to be preferred as it states more correctly the semantics of the query - i.e. "join tables t1 and t2".

The WHERE clause should be used for "filtering" results of the join - e.g.

... WHERE t2.some_col > 10

Also, as Constantin has said in another answer, the 4 queries would be different if the join was an OUTER join.

like image 56
Tony Andrews Avatar answered Oct 13 '22 00:10

Tony Andrews