tags: SQL

JOIN clause is used to combine rows from two or more tables, based on a related column between them.
Table 1: Order

OrderIDCustomerIDOrderNameProductName
12025101PeterABC
12030105RobertXYX
12032110JamesXYZ
12034115AndrewPQR
12035120MathewAAA

Table 2: Customer

CustomerIDCustomerNameCountry
100MessyMaxico
101PrinceTaiwan
103Maria FernandezTurkey
105JasmineParis
110Faf WeaselIndonesia
120Romen RocketRussia

Inner Join:

SELECT ord.OrderIDcust.CustomerNamecust.Countryord.ProductName 
FROM Order ord INNER JOIN Customer cust 
ON ord.CustomerID = cust.CustomerID;
OrderIDCustomerNameCountryProductName
12025PrinceTaiwanABC
12030JasmineParisXYX
12032Faf WeaselIndonesiaXYZ
12035Romen RocketRussiaAAA

Different Types of SQL JOINs

Here are the different types of the JOINs in SQL:

  • (INNER) JOIN: Returns records that have matching values in both tables
  • LEFT (OUTER) JOIN: Returns all records from the left table, and the matched records from the right table
  • RIGHT (OUTER) JOIN: Returns all records from the right table, and the matched records from the left table
  • FULL (OUTER) JOIN: Returns all records when there is a match in either left or right table
  • CROSS JOIN: Returns the Cartesian product of two or more joined tables. The cross join produces a table that merges each row from the first table with each second table row. It is not required to include any condition in CROSS JOIN.
  • SELF JOIN: Used to create a table by joining itself as there were two tables.

Notes

SELECT p.product_name, s.year, s.price
FROM Product p JOIN Sales s
ON p.product_id = s.product_id
 
--is faster than
 
SELECT product_name, year, price
FROM Product JOIN Sales
ON Product.product_id = Sales.product_id