Joins in sql
Joins are used to combine rows from two or more tables based on a related column between them.
Types of joins
1. Inner Join
Purpose: Retrieves rows that have matching values in both tables.
Example:
SELECT * FROM customers
INNER JOIN orders
ON customers.id = orders.customer_id;
2. Left Join (Left Outer Join)
Purpose: Fetches all records from the left table and the matched records from the right table. If there’s no match, the result is NULL on the right side.
Example:
SELECT * FROM customers
LEFT JOIN orders
ON customers.id = orders.customer_id;
3. Right Join (Right Outer Join)
Purpose: Fetches all records from the right table and the matched records from the left table. If there’s no match, the result is NULL on the left side.
Example:
SELECT * FROM customers
RIGHT JOIN orders
ON customers.id = orders.customer_id;
4. Full Join (Full Outer Join)
Purpose: Returns matching rows from both tables, plus all remaining records from both tables—even if there is no match.
Example:
SELECT * FROM customers
FULL OUTER JOIN orders
ON customers.id = orders.customer_id;
5. Cross Join
Purpose: Combines each row from the first table with every row from the second table (producing a "cartesian product").
Example:
SELECT * FROM customers
CROSS JOIN orders;
6. Exclusive Joins
Purpose: Returns only the records that do not have a match in the other table (exclusive of the overlap).
Left Exclusive Join:
SELECT * FROM customers
LEFT JOIN orders
ON customers.id = orders.customer_id
WHERE orders.customer_id IS NULL;
Right Exclusive Join:
SELECT * FROM customers
RIGHT JOIN orders
ON customers.id = orders.customer_id
WHERE customers.id IS NULL;
7. Self Join
Purpose: Joins a table to itself, useful for hierarchical data or when a table contains relationships within itself. Use table aliases to distinguish between the two instances.
Example:
SELECT s1.name AS mentor_name, s2.name AS student_name
FROM student AS s1
JOIN student AS s2
ON s1.s_id = s2.mentor_id;
Comments
Post a Comment