SQL Joins
SQL Joins
Customers Table:
CustomerID Name
1 Alice
2 Bob
3 Charlie
4 David
Orders Table:
101 1 Laptop
102 2 Phone
103 1 Tablet
104 3 Headphones
1. INNER JOIN
Definition:
An INNER JOIN returns only the rows that have matching values in both tables.
Example:
FROM Customers
Output:
Name Product
Alice Laptop
Alice Tablet
Bob Phone
Charlie Headphones
Explanation:
o Shows customers who have made orders (Alice, Bob, and Charlie).
Definition:
A LEFT JOIN returns all rows from the left table, and the matching rows from the right table. If there’s
no match, NULL is returned for columns from the right table.
Example:
FROM Customers
Output:
Name Product
Alice Laptop
Alice Tablet
Bob Phone
Charlie Headphones
David NULL
Explanation:
o David is shown with NULL in the Product column because he has no orders.
Definition:
A RIGHT JOIN returns all rows from the right table, and the matching rows from the left table. If
there’s no match, NULL is returned for columns from the left table.
Example:
FROM Customers
Output:
Name Product
Alice Laptop
Alice Tablet
Bob Phone
Charlie Headphones
Explanation:
o All orders are shown, and the customer names are filled in if they exist.
o There are no NULL rows in the Product column since every order has a customer.
Definition:
A FULL JOIN returns all rows from both tables, filling in NULL where there’s no match.
Example:
FROM Customers
Output:
Name Product
Alice Laptop
Alice Tablet
Bob Phone
Charlie Headphones
David NULL
Explanation:
o David is shown with NULL in the Product column since he didn’t make any orders.
5. CROSS JOIN
Definition:
A CROSS JOIN returns the Cartesian product of both tables, meaning it combines every row from the
first table with every row from the second table.
Example:
FROM Customers
Output:
Name Product
Alice Laptop
Alice Phone
Alice Tablet
Alice Headphones
Bob Laptop
Bob Phone
Bob Tablet
Bob Headphones
Charlie Laptop
Charlie Phone
Charlie Tablet
Charlie Headphones
David Laptop
David Phone
David Tablet
David Headphones
Explanation:
o Combines every customer with every order, even though there is no matching
condition.
Definition:
A SELF JOIN is a join where a table is joined with itself. It’s used to compare rows within the same
table.
Example:
FROM Customers A
Output:
Customer Customer2
Alice Bob
Alice Charlie
Alice David
Bob Alice
Bob Charlie
Bob David
Charlie Alice
Charlie Bob
Charlie David
David Alice
David Bob
David Charlie
Explanation:
o This query compares every customer with every other customer (excluding
themselves).
7. NATURAL JOIN
Definition:
A NATURAL JOIN automatically joins tables based on columns that have the same name and data
type. You don’t need to specify the join condition.
Example:
FROM Customers
Output:
Name Product
Alice Laptop
Alice Tablet
Bob Phone
Charlie Headphones
Explanation:
o The NATURAL JOIN automatically uses the CustomerID to join the tables.
o It works like an INNER JOIN, but you don’t need to specify the join condition
explicitly.