6.1 — INNER JOIN Basics
What You'll Learn
- How to use
INNER JOIN
to combine data from multiple tables - The Excel VLOOKUP analogy for joining tables
- Basic join syntax and examples
From Excel to SQL: VLOOKUP vs. JOIN
In Excel, you use VLOOKUP
to bring in data from another sheet. In SQL, you use JOIN
to combine tables based on a common column.
Example: Combine sales with product details
Table sales:
ProductID | Amount |
---|---|
101 | 120 |
102 | 80 |
103 | 50 |
Table products:
ProductID | ProductName |
---|---|
101 | Apples |
102 | Oranges |
104 | Bananas |
SQL:
sql
SELECT s.ProductID, p.ProductName, s.Amount
FROM sales s
INNER JOIN products as p
ON s.ProductID = p.ProductID;
INNER JOIN
returns only rows where theProductID
exists in both tables.
Note on Table Aliases
In SQL, you can assign a short alias to each table to make your queries easier to read and write. For example, sales as s
means you can refer to the sales
table as s
in the rest of your query. Similarly, products as p
lets you use p
as a shortcut for the products
table.
- This is especially helpful when joining multiple tables or when column names are the same in different tables.
- Use the alias when referencing columns, e.g.,
s.ProductID
orp.ProductName
. - It helps in the SELECT clause to indicate from which table the column should be used.
Key Points
INNER JOIN
is like VLOOKUP, but more powerful and flexible.- Always specify the join condition with
ON
. - You can join on any matching columns, not just IDs, not just on one-couple of columns.
Next Steps
Next, you’ll learn how to use LEFT JOIN
to include unmatched rows—just like handling missing data in Excel.