Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between SQL JOIN and querying from two tables

Tags:

sql

join

mysql

What is the difference between the query

SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo
FROM Persons
INNER JOIN Orders
ON Persons.P_Id=Orders.P_Id
ORDER BY Persons.LastName

and this one

SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo
FROM Persons, Orders
WHERE Persons.P_Id=Orders.P_Id
ORDER BY Persons.LastName
like image 308
Jeyanth Kumar Avatar asked Feb 28 '12 13:02

Jeyanth Kumar


People also ask

What is the query to join two tables?

Different Types of SQL JOINs(INNER) JOIN : Returns records that have matching values in both tables. LEFT (OUTER) JOIN : Returns all records from the left table, and the matched records from the right table. RIGHT (OUTER) JOIN : Returns all records from the right table, and the matched records from the left table.

Which SQL query is faster filter on join criteria or WHERE clause?

I ran some tests and the results show that it is actually very close, but the WHERE clause is actually slightly faster! =) I absolutely agree that it makes more sense to apply the filter on the WHERE clause, I was just curious as to the performance implications.

Which is better join or inner query?

The retrieval time of the query using joins almost always will be faster than that of a subquery. By using joins, you can maximize the calculation burden on the database i.e., instead of multiple queries using one join query.

What is the correct syntax to connect two tables together in a SQL Select query?

The join is done by the JOIN operator. In the FROM clause, the name of the first table ( product ) is followed by a JOIN keyword then by the name of the second table ( category ). This is then followed by the keyword ON and by the condition for joining the rows from the different tables.


2 Answers

There is a small difference in syntax, but both queries are doing a join on the P_Id fields of the respective tables.

In your second example, this is an implicit join, which you are constraining in your WHERE clause to the P_Id fields of both tables.

The join is explicit in your first example and the join clause contains the constraint instead of in an additional WHERE clause.

like image 97
Oded Avatar answered Sep 23 '22 05:09

Oded


They are basically equivalent. In general, the JOIN keywords enables you to be more explicit about direction (LEFT, RIGHT) and type (INNER, OUTER, CROSS) of your join.

like image 35
Matthias Meid Avatar answered Sep 20 '22 05:09

Matthias Meid