Practical SQL

NATURAL JOIN in SQL

Constantin LunguUpdated 1 min read

Photo by micheile henderson on Unsplash

Another lesser known JOIN - the natural join. But maybe the NATURAL JOIN is not as obscure after all, since it has its own keyword, at least in a couple of SQL dialects - see PostgreSQL portrayed below (sorry, it's not supported in BigQuery, but it does recognize it).

So what's special about it? Well, it joins the tables based on columns that have the same name (and datatype) in the two tables. That is, we don't need to specify any join conditions.

Watch out because if there are no columns with the same name and datatype, it defaults to a Cartesian product is produced (which is what CROSS JOIN does).

WITH stores AS (
SELECT 1 AS store_id, 'Flagship store - NY' AS store_name UNION ALL
SELECT 2 AS store_id, 'Main St. - LA' AS store_name UNION ALL
SELECT 3 AS store_id, 'Michigan Ave. - Chicago' AS store_name ),

employees AS (
SELECT 1 AS employee_id, 1 AS store_id UNION ALL
SELECT 2 AS employee_id, 2 AS store_id UNION ALL
SELECT 3 AS employee_id, 3 AS store_id
)

SELECT employee_id, store_id, store_name
FROM stores
NATURAL JOIN employees

Output: employee 1 with store 1 Flagship store - NY, employee 2 with store 2 Main St. - LA, and employee 3 with store 3 Michigan Ave. - Chicago.


Enjoyed this? Here are some related articles you might find useful:

Comments

chandravathi Yerramasu · 20 June 2024

It was very beneficial and how to deal the data regarding to requirements, by this article I came to know usage of a particular clause or function accordingly, thanks for providing these kind of articles.

Constantin Lungu · 20 June 2024

Thanks for reading!