Natural Join and USING Clause

The SQL NATURAL JOIN is a type of JOIN that is structured in such a way that, columns with the same name of associated tables will appear only once and match is automatically based on columns with exact same name and data type. The matching is done implicit and query cannot provide column name.

Natural Join

  • The joined tables have one or more pairs of identical column names.
  • The columns have same data type.
  • Cannot use ON clause or USING clause in a natural join.
  • All the common columns are matched.

You can read more about natural join on wikipedia

USING Clause

The USING Clause can be used to specify only those columns that should be used for join. The USING clause cannot be used with NATURAL join. The column name(s) are explicitly defined when USING clause is used and columns should not use the table aliases, since each column should be present in all joined tables.

DROP TABLE IF EXISTS Departments;
CREATE TABLE IF NOT EXISTS Departments
(
 DepartmentId Integer Primary Key AutoIncrement
,DepartmentName TEXT
);
 
 
INSERT INTO Departments(DepartmentName) VALUES('Administration');
INSERT INTO Departments(DepartmentName) VALUES('Sales & Marketing');
INSERT INTO Departments(DepartmentName) VALUES('HR');
INSERT INTO Departments(DepartmentName) VALUES('Accounts');
 
DROP TABLE IF EXISTS EmployeeMaster;
CREATE TABLE IF NOT EXISTS EmployeeMaster
(
EmployeeId Integer Primary Key AutoIncrement,
FirstName Text,
LastName Text,
DepartmentId Integer,
ReportsTo Integer
);
 
INSERT INTO EmployeeMaster values (1,'John','Dekota', 2,7);
INSERT INTO EmployeeMaster values (2,'Mary','Denware',3,2);
INSERT INTO EmployeeMaster values (3,'Scott','Hamilton',2,7);
INSERT INTO EmployeeMaster values (4,'Guru','Manna',3,2);
INSERT INTO EmployeeMaster values (5,'Robert','Olipo',1,3);
INSERT INTO EmployeeMaster values (6,'Mark','Netcal',2,7);
INSERT INTO EmployeeMaster values (7,'Peter','adam',3,2);
INSERT INTO EmployeeMaster values (8,'Martin','Jerico',2,7);
INSERT INTO EmployeeMaster values (9,'Davis','Ocee',1,3);

SELECT * FROM EmployeeMaster NATURAL JOIN Departments;

SELECT * FROM EmployeeMaster JOIN Departments USING (DepartmentId);

The both above SELECT statements will produce the same result, joining on DepartmentId and showing only one DepartmentId column.

Query Results for Natural Join and USING Clause

The above SELECT statements can also be written as following and will produce the same result set.

SELECT e.EmployeeId , e.FirstName, e.LastName, e.DepartmentId, e.ReportsTo , d.DepartmentName
FROM EmployeeMaster e
JOIN Departments d
ON e.DepartmentId = d.DepartmentId;

The natural join and using clause can make SQL easy to read and maintain.