SQL · Module 7 · Lesson 21 min read

INNER JOIN

What INNER JOIN does

Combines rows from two tables where the join condition matches. Rows without a match on either side are left out.

SQL
SELECT e.title, u.name
FROM expenses e
INNER JOIN users u ON u.id = e.user_id;
  • INNER is optional: JOIN means INNER JOIN
  • ON – the condition linking the tables (usually FK = PK)

Think of it like this

For every expense, find the user whose id equals the expense's user_id, and glue the two rows together side by side.

Table aliases are essential

  • FROM expenses e JOIN users u – short names
  • Prefix columns with the alias (e.title, u.name), especially when both tables have a column with the same name (id, name, created_at) — otherwise you get "column reference is ambiguous"

Joining more tables

Chain joins one after another:

vbnet
FROM expenses e
JOIN users u      ON u.id = e.user_id
JOIN categories c ON c.id = e.category_id

Things that disappear with INNER JOIN

  • Users with no expenses (Maya, Hari)
  • Expenses whose category_id is NULL Need them? Use LEFT JOIN (next lesson).

USING shortcut

If both columns have the same name: JOIN accounts USING (user_id). The column then appears once in the result.

Join + filter + group

Joins combine naturally with WHERE, GROUP BY and ORDER BY — most real reports look like: FROM … JOIN … WHERE … GROUP BY … HAVING … ORDER BY …

Example

SQL
-- Each expense with the user's name
SELECT e.title, e.amount, u.name
FROM expenses e
JOIN users u ON u.id = e.user_id
ORDER BY e.amount DESC
LIMIT 3;
-- Paragliding       | 8500.00 | Ravi Thapa
-- Flight to Pokhara | 7800.00 | Sita Gurung
-- Running shoes     | 6500.00 | Asha Sharma

-- Three tables: expense + user + category
SELECT u.name, c.name AS category, e.title, e.amount
FROM expenses e
JOIN users u      ON u.id = e.user_id
JOIN categories c ON c.id = e.category_id
WHERE u.city = 'Kathmandu' AND e.spent_on >= '2026-11-01'
ORDER BY e.spent_on;

-- ❌ Ambiguous column: both tables have "id"
-- SELECT id, name FROM expenses JOIN users ON users.id = expenses.user_id;
-- ✅ Prefix it
SELECT e.id, u.name FROM expenses e JOIN users u ON u.id = e.user_id LIMIT 2;

-- Join + group: total per city
SELECT u.city, count(*) AS expenses, sum(e.amount) AS total
FROM expenses e
JOIN users u ON u.id = e.user_id
GROUP BY u.city
ORDER BY total DESC;
-- Kathmandu 18 | 46040.00, Pokhara 7 | 22630.00, Lalitpur 6 | 7940.00

-- USING: same column name in both tables
SELECT user_id, a.name AS account, b.title AS bill
FROM accounts a
JOIN bills b USING (user_id)
WHERE user_id = 1;

-- INNER JOIN drops users with no expenses: only 4 of 6 users appear
SELECT count(DISTINCT u.id) FROM users u JOIN expenses e ON e.user_id = u.id;  -- 4