Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

the difference between comma and join in sql

Tags:

sql

join

what is the difference between using comma or join between two different tables.

such as these two codes:

SELECT studentId, tutorId FROM student, tutor;


SELECT studentId, tutorId FROM student JOIN tutor;
like image 587
user2749139 Avatar asked Dec 09 '13 09:12

user2749139


People also ask

What does a comma mean in SQL?

Commas act as a separator in SQL. There should not be any commas between FROM and the first table name or after the final table name. The same idea applies to column definition: when you create a table, be sure not to type an extra comma after the final column name. This is a really common error.

What is a comma join?

The joining comma is only slightly different from the listing comma. It is used to join two complete sentences into a single sentence, and it must be followed by a suitable connecting word. The connecting words which can be used in this way are and, or, but, while and yet.

What is Comma Separated join in SQL?

A comma separated join (CROSS JOIN) is great when you want to end up with ALL COMBINATIONS of both tables, which isn't often. It is great when you're in an environment where the DBA policies do not allow variables (Yes, they exist!). Simply create a 1 row temp table or CTE to contain all variables.

What are the 4 types of joins in SQL?

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


2 Answers

There's no real difference WHEN executing them, but there is a readability, consistency and error mitigating issue at work:

Imagine you had 4 tables If you used the old fashioned way of doing an INNER JOIN, you would end up with:

SELECT col1, col2
FROM tab1, tab2, tab3,tab4
WHERE tab1.id=tab2.tab1_id
AND tab4.id = tab2.tab3_id
AND tab4.id = tab3.tab4_id;

Using explicit INNER JOINS it would be:

SELECT col1, col2
FROM tab1
INNER JOIN tab2 ON tab1.id = tab2.tab1_id
INNER JOIN tab3 ON tab3.id = tab2.tab3_id
INNER JOIN tab4 ON tab4.id = tab3.tab4_id;

The latter shows you right in front of the table exactly what is it JOINing with. It has improved readability, and much less error prone, since it's harder to forget to put the ON clause, than to add another AND in WHERE or adding a wrong condition altogether (like i did in the query above :).

Additionally, if you are doing other types of JOINS, using the explicit way of writing them, you just need to change the INNER to something else, and the code is consistently constructed.

like image 81
Filipe Silva Avatar answered Nov 03 '22 00:11

Filipe Silva


Based on the specific code you gave, there is no difference at all.

However, using the JOIN operator syntax, you are allowed to specify the join conditions, which is very important when doing LEFT JOINs or RIGHT JOINs

like image 25
Matteo Tassinari Avatar answered Nov 03 '22 00:11

Matteo Tassinari