SQL INNER JOIN πΈοΈ¶
Mentor's Note: Data is rarely stored in a single table. You have "Customers" in one place and "Orders" in another.
INNER JOINis the handshake that introduces them. It brings together only the data that matches in both places. π‘
π The Scenario: The Dinner Date π½οΈ¶
Imagine you are arranging a dinner. - Table A (People): A list of all your friends. - Table B (RSVPs): A list of people who said "Yes". - INNER JOIN: The people who actually show up to eat (Friends AND RSVP'd). If a friend didn't RSVP, they aren't on the list. If an RSVP has no name, it's ignored. π«
π¨ Visual Logic: The Intersection¶
flowchart LR
A((Table A<br/>ID:1,2)) -.->|match| I((Intersection<br/>ID:1))
B((Table B<br/>ID:1,3)) -.->|match| I
A2[Only A: ID 2]
B3[Only B: ID 3]
style A fill:#4caf50,stroke:#333,stroke-width:3px
style B fill:#2196f3,stroke:#333,stroke-width:3px
style I fill:#ffbc3b,stroke:#333,stroke-width:4px
Only data present in BOTH tables (the highlighted intersection) is included in the result.
π» 1. The Basic Syntax¶
Example: Who ordered what?¶
-- Scenario: Show Customer Name and their Order Date
SELECT customers.name, orders.order_date
FROM customers
INNER JOIN orders
ON customers.id = orders.customer_id;
π» 2. Joining Multiple Tables (The Chain) π¶
You can join as many tables as you like!
-- Scenario: Customer -> Order -> Product
SELECT C.name, O.order_date, P.product_name
FROM customers C
JOIN orders O ON C.id = O.customer_id
JOIN order_details D ON O.id = D.order_id
JOIN products P ON D.product_id = P.id;
β οΈ Important Rules¶
- Ambiguity: If both tables have a column named
id, you must usetable.idoralias.id. - Data Loss: Any row that does not find a match is hidden. (Use OUTER JOIN if you want to keep them).