Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use JOIN rather than inner queries

Tags:

sql-server

I find myself unwilling to push to using JOIN when I can easily solve the same problem by using an inner query:

e.g.

SELECT COLUMN1, ( SELECT COLUMN1 FROM TABLE2 WHERE TABLE2.ID = TABLE1.TABLE2ID ) AS COLUMN2 FROM TABLE1;

My question is, is this a bad programming practice? I find it easier to read and maintain as opposed to a join.

UPDATE

I want to add that there's some great feedback in here which in essence is pushing be back to using JOIN. I am finding myself less and less involved with using TSQL directly these days as of a result of ORM solutions (LINQ to SQL, NHibernate, etc.), but when I do it's things like correlated subqueries which I find are easier to type out linearly.

like image 514
Keith Adler Avatar asked Feb 24 '10 17:02

Keith Adler


People also ask

What are the reasons that you should use a subquery vs a join?

If you need to combine related information from different rows within a table, then you can join the table with itself. Use subqueries when the result that you want requires more than one query and each subquery provides a subset of the table involved in the query.

Why LEFT JOIN is better than inner join?

You'll use INNER JOIN when you want to return only records having pair on both sides, and you'll use LEFT JOIN when you need all records from the “left” table, no matter if they have pair in the “right” table or not.

Why We Use join query?

A JOIN clause is used to combine rows from two or more tables, based on a related column between them. Notice that the "CustomerID" column in the "Orders" table refers to the "CustomerID" in the "Customers" table. The relationship between the two tables above is the "CustomerID" column.

Is join more efficient than where?

“Is there a performance difference between putting the JOIN conditions in the ON clause or the WHERE clause in MySQL?” No, there's no difference. The following queries are algebraically equivalent inside MySQL and will have the same execution plan.


2 Answers

Personally, I find this incredibly difficult to read. It isn't the structure a SQL developer expects. By using JOIN, you are keeping all of your table sources in a single spot instead of spreading it throughout your query.

What happens if you need to have three or four joins? Putting all of those into the SELECT clause is going to get hairy.

like image 198
Jordan Parmer Avatar answered Oct 08 '22 01:10

Jordan Parmer


A join is usually faster than a correlated subquery as it acts on the set of rows rather than one row at a time. I would never let this code go to my production server.

And I find a join much much easier to read and maintain.

like image 26
HLGEM Avatar answered Oct 08 '22 00:10

HLGEM