What Are Joins in SQL?
Joins in SQL are used to combine rows from two or more tables based on a related column (usually a foreign key). This allows you to query and analyze data across multiple tables as if they were one.
Why Use Joins?
-
To retrieve data that is spread across multiple tables.
-
To enforce and use relationships between tables (like customers and orders).
-
To avoid data duplication by normalizing tables.
Types of Joins
1. INNER JOIN
Returns only rows that have matching values in both tables.
SELECT orders.order_id, customers.name
FROM orders
INNER JOIN customers ON orders.customer_id = customers.customer_id;
2. LEFT JOIN (or LEFT OUTER JOIN)
Returns all rows from the left table, and matching rows from the right table. If no match, returns NULL.
SELECT customers.name, orders.order_id
FROM customers
LEFT JOIN orders ON customers.customer_id = orders.customer_id;
3. RIGHT JOIN (or RIGHT OUTER JOIN)
Returns all rows from the right table, and matching rows from the left table. If no match, returns NULL.
SELECT customers.name, orders.order_id
FROM customers
RIGHT JOIN orders ON customers.customer_id = orders.customer_id;
4. FULL JOIN (or FULL OUTER JOIN)
Returns all rows when there is a match in one of the tables. If no match, fills with NULL.
SELECT customers.name, orders.order_id
FROM customers
FULL OUTER JOIN orders ON customers.customer_id = orders.customer_id;
5. CROSS JOIN
Returns the Cartesian product of the two tables—every row in the first table is combined with every row in the second.
SELECT a.name, b.product
FROM customers a
CROSS JOIN products b;
