Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use SQL natural join instead of join .. on?

Tags:

sql

I'm studying SQL for a database exam and the way I've seen SQL is they way it looks on this page:

http://en.wikipedia.org/wiki/Star_schema IE join written the way Join <table name> On <table attribute> and then the join condition for the selection. My course book and my exercises given to me from the academic institution however, use only natural join in their examples. So when is it right to use natural join? Should natural join be used if the query can also be written using JOIN .. ON ?

Thanks for any answer or comment

like image 441
Niklas Rosencrantz Avatar asked May 09 '12 06:05

Niklas Rosencrantz


4 Answers

A natural join will find columns with the same name in both tables and add one column in the result for each pair found. The inner join lets you specify the comparison you want to make using any column.

like image 173
Saulo Vallory Avatar answered Nov 09 '22 02:11

Saulo Vallory


IMO, the JOIN ON syntax is much more readable and maintainable than the natural join syntax. Natural joins is a leftover of some old standards, and I try to avoid it like the plague.

like image 33
baldy Avatar answered Nov 09 '22 02:11

baldy


A natural join will find columns with the same name in both tables and add one column in the result for each pair found. The inner join lets you specify the comparison you want to make using any column.

The JOIN keyword is used in an SQL statement to query data from two or more tables, based on a relationship between certain columns in these tables.

Different Joins

*  JOIN: Return rows when there is at least one match in both tables
* LEFT JOIN: Return all rows from the left table, even if there are no matches in the right table
* RIGHT JOIN: Return all rows from the right table, even if there are no matches in the left table
* FULL JOIN: Return rows when there is a match in one of the tables

INNER JOIN http://www.w3schools.com/sql/sql_join_inner.asp

FULL JOIN http://www.w3schools.com/sql/sql_join_full.asp

like image 2
Okky Avatar answered Nov 09 '22 01:11

Okky


A natural join is said to be an abomination because it does not allow qualifying key columns, which makes it confusing. Because you never know which "common" columns are being used to join two tables simply by looking at the sql statement.

like image 1
Helen Cui Avatar answered Nov 09 '22 02:11

Helen Cui