Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL INNER JOIN ON and USING

Tags:

sql

Say I have tables and I join them with inner join. What is the advantage of using "ON" over "USING". Or are they the same in all sense?

like image 286
user618677 Avatar asked Oct 19 '11 18:10

user618677


People also ask

Can we use and with inner join in SQL?

With the AND in the inner join you can specify it even more. Join the tables on the columns, where A1. Column = 'TASK' and throw away the rest. You could just as easily move the AND to the WHERE -Clause.

What is the difference between on and using join clause?

The USING clause: This allows you to specify the join key by name. The ON clause: This syntax allows you to specify the column names for join keys in both tables.

Can I use inner join without on?

In MySQL, it's possible to have a JOIN statement without ON as ON is an optional clause. You can just simplly JOIN two tables like this: SELECT * FROM table_a JOIN table_b; It will match each row from table_a to every row in table_b .


2 Answers

USING is an equijoin and causes duplicate columns to be removed from the resultset (arguably this makes it "more relational").

ON is a theta join (i.e. join condition need not be equality and may involve columns with differing names) and allows duplicate columns to appear in the resultset.

like image 197
onedaywhen Avatar answered Oct 08 '22 04:10

onedaywhen


USING requires the names of the columns in both tables to be identical:

SELECT *
FROM   employee 
   INNER JOIN department 
      USING (DepartmentID);

whereas ON allows you to designate any columns to join on:

SELECT *
FROM   employee 
   JOIN department 
      ON employee.DepartmentID = department.ID;

In short, USING is more succinct, but ON is more flexible.

http://en.wikipedia.org/wiki/Join_(SQL)#Equi-join

like image 28
ewok Avatar answered Oct 08 '22 04:10

ewok