SQL: JOIN and Relationships
1. What is a JOIN?
A JOIN is a method of retrieving data by connecting two or more tables. Data is combined based on common columns, typically foreign keys.
2. Major Types of JOINs
INNER JOIN
Returns only the rows that have matching values in both tables.
SELECT orders.id, users.name
FROM orders
INNER JOIN users ON orders.user_id = users.id;
LEFT (OUTER) JOIN
Returns all rows from the left table and the matched rows from the right table. If there is no match, the result is NULL for columns from the right table.
SELECT users.name, orders.product_name
FROM users
LEFT JOIN orders ON users.id = orders.user_id;
3. Relationships
- 1:1 (One-to-One): A relationship such as between a user and their specific user settings.
- 1:N (One-to-Many): A relationship where one user can have multiple orders. (The most common type)
- N:M (Many-to-Many): A relationship such as between students and classes (requires a bridging or mapping table in between).