---
title: "SQL Joins Explained with Examples"
url: https://www.khanwaseem.com/blog/database/sql-joins-explained
author: "khan Waseem"
published: 2026-12-01
updated: 2026-12-01
topics: ["Database", "Blog"]
description: "Learn SQL joins with one small shop database: INNER, LEFT, RIGHT, FULL OUTER, CROSS and SELF joins, finding rows with no match, joining many tables, ON vs WHERE, and the duplicate-row trap, with every query run on…"
---

# SQL Joins Explained with Examples

Table of Contents

[Toggle](#)

- [Introduction:](#introduction)
- [Part 1: The Sample Data](#part-1-the-sample-data)[1. Two Small Tables:](#1-two-small-tables)
- [2. Join Syntax:](#2-join-syntax)

- [Part 2: The Main Join Types](#part-2-the-main-join-types)[3. INNER JOIN: Only Matching Rows:](#3-inner-join-only-matching-rows)
- [4. LEFT JOIN: Keep Everything on the Left:](#4-left-join-keep-everything-on-the-left)
- [5. Finding Rows with No Match:](#5-finding-rows-with-no-match)
- [6. RIGHT JOIN: Keep Everything on the Right:](#6-right-join-keep-everything-on-the-right)
- [7. FULL OUTER JOIN: Keep Everything:](#7-full-outer-join-keep-everything)
- [8. A Quick Summary:](#8-a-quick-summary)

- [Part 3: Special Joins](#part-3-special-joins)[9. CROSS JOIN: Every Combination:](#9-cross-join-every-combination)
- [10. SELF JOIN: A Table Joined to Itself:](#10-self-join-a-table-joined-to-itself)

- [Part 4: Real-World Queries](#part-4-real-world-queries)[11. Joining More Than Two Tables:](#11-joining-more-than-two-tables)
- [12. Joins with GROUP BY:](#12-joins-with-group-by)

- [Part 5: Common Mistakes](#part-5-common-mistakes)[13. Filtering in WHERE vs ON:](#13-filtering-in-where-vs-on)
- [14. Duplicate Rows Inflating Totals:](#14-duplicate-rows-inflating-totals)
- [15. Other Tips:](#15-other-tips)

- [Conclusion:](#conclusion)

## Introduction:

A well-designed database doesn’t keep everything in one giant table. Customers live in a `customers` table, orders in an `orders` table, and products in a `products` table. Each fact is stored **once**, and tables point at each other using IDs. This keeps data tidy and avoids contradictions, but it raises an obvious question: how do you answer “which customer placed which order, for which product?” when that information is spread across three tables?

The answer is a **JOIN**. A join combines rows from two or more tables based on a related column, so you can read them as if they were one table.

Joins are the single most important skill in SQL after `SELECT` itself, and they are asked about in almost every backend and data interview. In this lesson we will build one small shop database and use it to learn every type of join: INNER, LEFT, RIGHT, FULL OUTER, CROSS and SELF. Then we will join several tables, use joins with `GROUP BY`, and look at the two most common join mistakes.

It builds on our lessons on [What is SQL?](https://blog.khanwaseem.com/what-is-sql/) and [Database Indexing](https://blog.khanwaseem.com/database-indexing/). Every query below was run on **PostgreSQL 16**, and the results shown are the real output. Apart from small notes, the same SQL works in MySQL, SQLite and SQL Server.

## Part 1: The Sample Data

### 1. Two Small Tables:

We’ll start with customers and their orders:

```javascript
CREATE TABLE customers (id int PRIMARY KEY, name text, city text);
CREATE TABLE orders (id int PRIMARY KEY, customer_id int, amount numeric(8,2), ordered_on date);

INSERT INTO customers VALUES
  (1, 'Aisha', 'Mumbai'),
  (2, 'Rahul', 'Delhi'),
  (3, 'Sara',  'Pune'),
  (4, 'Imran', 'Mumbai');

INSERT INTO orders VALUES
  (101, 1,  450.00, '2026-11-02'),
  (102, 1, 1200.00, '2026-11-15'),
  (103, 2,  300.00, '2026-11-20'),
  (104, 9,  999.00, '2026-11-21');Code language: JavaScript (javascript)
```

`orders.customer_id` points to `customers.id`. That link is what we join on. Look closely at the data, because each type of join treats these cases differently:

- **Aisha** has two orders.

- **Rahul** has one order.

- **Sara** and **Imran** have **no orders**.

- Order **104** belongs to customer **9**, who **doesn’t exist** (maybe the customer was deleted). In a real system a foreign key constraint would prevent this, but messy data like this is common, and joins are how you find it.

### 2. Join Syntax:

Every join has the same shape:

```
SELECT columns
FROM left_table
JOIN_TYPE right_table ON matching_condition;
```

- The table after `FROM` is the **left** table, and the one after `JOIN` is the **right** table.

- `ON` says which rows belong together, usually “this ID equals that ID”.

- Short **aliases** like `c` and `o` keep queries readable: `customers c` means “call this table `c`“.

## Part 2: The Main Join Types

### 3. INNER JOIN: Only Matching Rows:

An **INNER JOIN** returns only the rows that have a match in **both** tables:

```php
SELECT c.name, o.id AS order_id, o.amount
FROM customers c
INNER JOIN orders o ON o.customer_id = c.id
ORDER BY o.id;

--  name  | order_id | amount
-- -------+----------+---------
--  Aisha |      101 |  450.00
--  Aisha |      102 | 1200.00
--  Rahul |      103 |  300.00
-- (3 rows)Code language: PHP (php)
```

Notice three things:

- Aisha appears **twice**, once for each of her orders. A join produces one row per **matching pair**.

- Sara and Imran are **missing**, because they have no orders.

- Order 104 is **missing**, because there’s no customer 9.

`INNER JOIN` is the default, so writing just `JOIN` means the same thing. Use it when you only care about rows that are connected on both sides, such as “show all orders with their customer’s name”.

### 4. LEFT JOIN: Keep Everything on the Left:

A **LEFT JOIN** (or `LEFT OUTER JOIN`) returns **every** row from the left table, plus the matching rows from the right. Where there’s no match, the right side’s columns are filled with `NULL`:

```php
SELECT c.name, o.id AS order_id, o.amount
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
ORDER BY c.id, o.id;

--  name  | order_id | amount
-- -------+----------+---------
--  Aisha |      101 |  450.00
--  Aisha |      102 | 1200.00
--  Rahul |      103 |  300.00
--  Sara  |          |
--  Imran |          |
-- (5 rows)Code language: PHP (php)
```

Now Sara and Imran appear, with empty (`NULL`) order columns. LEFT JOIN is the most-used outer join, because the question is so often “show me **all** X, and their Y **if they have any**“: all customers and their orders, all products and their reviews, all students and their grades.

### 5. Finding Rows with No Match:

A very useful trick: LEFT JOIN, then keep only the rows where the right side is `NULL`. That gives you the left rows that have **no** match at all:

```php
SELECT c.name
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
WHERE o.id IS NULL
ORDER BY c.id;

--  name
-- -------
--  Sara
--  Imran
-- (2 rows)Code language: PHP (php)
```

These are customers who have never ordered, which is perfect for a “we miss you” email campaign. The same result can be written with `NOT EXISTS`, which many people find clearer and which databases optimise just as well:

```
SELECT name
FROM customers c
WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id)
ORDER BY id;

-- Sara, Imran
```

Always check a primary key column (like `o.id`) for `NULL`, not a column that could legitimately be empty in real data.

### 6. RIGHT JOIN: Keep Everything on the Right:

A **RIGHT JOIN** is the mirror image: every row from the **right** table, plus matches from the left:

```php
SELECT c.name, o.id AS order_id, o.customer_id
FROM customers c
RIGHT JOIN orders o ON o.customer_id = c.id
ORDER BY o.id;

--  name  | order_id | customer_id
-- -------+----------+-------------
--  Aisha |      101 |           1
--  Aisha |      102 |           1
--  Rahul |      103 |           2
--        |      104 |           9
-- (4 rows)Code language: PHP (php)
```

Every order appears, and order 104 shows an empty name: an **orphan** order whose customer is missing. This is a quick way to find broken references in your data.

In practice, most developers rarely write RIGHT JOIN. Any right join can be rewritten as a left join by swapping the table order (`FROM orders o LEFT JOIN customers c ...`), and queries are easier to read when they consistently start from the “main” table.

### 7. FULL OUTER JOIN: Keep Everything:

A **FULL OUTER JOIN** keeps every row from **both** tables. Matches are combined, and anything without a partner is still included, with `NULL`s on the missing side:

```php
SELECT c.name, o.id AS order_id
FROM customers c
FULL OUTER JOIN orders o ON o.customer_id = c.id
ORDER BY c.id NULLS LAST, o.id;

--  name  | order_id
-- -------+----------
--  Aisha |      101
--  Aisha |      102
--  Rahul |      103
--  Sara  |
--  Imran |
--        |      104
-- (6 rows)Code language: PHP (php)
```

We see customers without orders **and** orders without customers in one result. FULL OUTER JOIN is mostly used for comparing and reconciling two data sets, for example matching bank transactions against your own payment records to find anything missing on either side.

PostgreSQL, SQL Server, Oracle and SQLite (3.39 and later) support it. **MySQL does not**; there you combine a LEFT JOIN and a RIGHT JOIN with `UNION`.

### 8. A Quick Summary:

Using our data (4 customers, 4 orders):

- **INNER JOIN:** 3 rows. Only matched pairs.

- **LEFT JOIN:** 5 rows. All customers, plus matching orders.

- **RIGHT JOIN:** 4 rows. All orders, plus matching customers.

- **FULL OUTER JOIN:** 6 rows. Everything from both sides.

If you remember the Venn diagram picture of two overlapping circles: INNER is the overlap, LEFT is the whole left circle, RIGHT is the whole right circle, and FULL is both circles. (The picture breaks down a little when one row matches many, as Aisha does, but it is a good starting point.)

## Part 3: Special Joins

### 9. CROSS JOIN: Every Combination:

A **CROSS JOIN** has no `ON` condition. It pairs **every** row of the first table with **every** row of the second, which is called a **Cartesian product**:

```javascript
CREATE TABLE sizes (size text);
CREATE TABLE colors (color text);
INSERT INTO sizes VALUES ('S'), ('M'), ('L');
INSERT INTO colors VALUES ('Black'), ('White');

SELECT s.size, c.color
FROM sizes s
CROSS JOIN colors c
ORDER BY c.color, s.size;

--  size | color
-- ------+-------
--  L    | Black
--  M    | Black
--  S    | Black
--  L    | White
--  M    | White
--  S    | White
-- (6 rows)Code language: JavaScript (javascript)
```

3 sizes × 2 colours = 6 product variants. Cross joins are handy for generating combinations, such as every product in every store, or every day in a month for every employee. But be careful: two tables of 10,000 rows each produce **100 million** rows. Forgetting an `ON` condition by accident (or writing `FROM a, b` with no `WHERE`) creates the same explosion.

### 10. SELF JOIN: A Table Joined to Itself:

Sometimes rows in a table point to **other rows in the same table**. A classic example is employees and their managers, where a manager is also an employee:

```php
CREATE TABLE employees (id int PRIMARY KEY, name text, manager_id int);
INSERT INTO employees VALUES
  (1, 'Meera', NULL),
  (2, 'Arjun', 1),
  (3, 'Kavya', 1),
  (4, 'Dev',   2);

SELECT e.name AS employee, m.name AS manager
FROM employees e
LEFT JOIN employees m ON m.id = e.manager_id
ORDER BY e.id;

--  employee | manager
-- ----------+---------
--  Meera    |
--  Arjun    | Meera
--  Kavya    | Meera
--  Dev      | Arjun
-- (4 rows)Code language: PHP (php)
```

There’s no special `SELF JOIN` keyword. You simply use the same table twice with **two different aliases**: `e` for the employee and `m` for the manager. We used a LEFT JOIN so that Meera, the CEO with no manager, still appears. Self joins are also used for things like categories with parent categories, or comparing rows within the same table (for example, two orders from the same customer on the same day).

## Part 4: Real-World Queries

### 11. Joining More Than Two Tables:

Real queries often chain several joins. Let’s add products and the items in each order:

```javascript
CREATE TABLE products (id int PRIMARY KEY, name text, price numeric(8,2));
CREATE TABLE order_items (order_id int, product_id int, qty int);

INSERT INTO products VALUES
  (1, 'Keyboard', 150.00), (2, 'Mouse', 150.00),
  (3, 'Monitor', 1200.00), (4, 'Webcam', 300.00);

INSERT INTO order_items VALUES
  (101, 1, 1), (101, 2, 2), (102, 3, 1), (103, 4, 1);Code language: JavaScript (javascript)
```

Now we can answer “who bought what?” by walking from customers to orders to order items to products:

```php
SELECT c.name, o.id AS order_id, p.name AS product, oi.qty
FROM customers c
JOIN orders o       ON o.customer_id = c.id
JOIN order_items oi ON oi.order_id   = o.id
JOIN products p     ON p.id          = oi.product_id
ORDER BY o.id, p.id;

--  name  | order_id | product  | qty
-- -------+----------+----------+-----
--  Aisha |      101 | Keyboard |   1
--  Aisha |      101 | Mouse    |   2
--  Aisha |      102 | Monitor  |   1
--  Rahul |      103 | Webcam   |   1
-- (4 rows)Code language: PHP (php)
```

Each `JOIN ... ON` adds one more table to the chain. `order_items` is a **junction table**: it connects orders and products, because one order can contain many products and one product can appear in many orders (a many-to-many relationship).

### 12. Joins with GROUP BY:

Joins become really powerful when combined with aggregates. How many orders has each customer placed, and how much have they spent in total, **including** customers who haven’t ordered?

```php
SELECT c.name,
       COUNT(o.id) AS orders,
       COALESCE(SUM(o.amount), 0) AS total_spent
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
GROUP BY c.id, c.name
ORDER BY total_spent DESC, c.id;

--  name  | orders | total_spent
-- -------+--------+-------------
--  Aisha |      2 |     1650.00
--  Rahul |      1 |      300.00
--  Sara  |      0 |           0
--  Imran |      0 |           0
-- (4 rows)Code language: PHP (php)
```

Two small details make this correct:

- **`COUNT(o.id)`, not `COUNT(*)`.** `COUNT(*)` counts rows, and the LEFT JOIN creates one row for Sara (with `NULL`s), so it would report 1 order. `COUNT(o.id)` only counts non-NULL order IDs, giving 0.

- **`COALESCE(SUM(...), 0)`.** The sum of no values is `NULL`, and `COALESCE` turns it into a friendly 0.

## Part 5: Common Mistakes

### 13. Filtering in WHERE vs ON:

This is the most common LEFT JOIN bug. Suppose we want all customers, with only their orders above ₹400. Here’s the obvious attempt:

```php
SELECT c.name, o.id AS order_id, o.amount
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
WHERE o.amount > 400
ORDER BY c.id;

--  name  | order_id | amount
-- -------+----------+---------
--  Aisha |      101 |  450.00
--  Aisha |      102 | 1200.00
-- (2 rows)Code language: PHP (php)
```

Rahul, Sara and Imran have disappeared, so our LEFT JOIN quietly became an INNER JOIN. Why? `WHERE` runs **after** the join. Rows with no order have `o.amount = NULL`, and `NULL > 400` is not true, so `WHERE` throws them away.

The fix is to put the condition **in the `ON` clause**, so it only decides which orders get matched:

```php
SELECT c.name, o.id AS order_id, o.amount
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id AND o.amount > 400
ORDER BY c.id;

--  name  | order_id | amount
-- -------+----------+---------
--  Aisha |      101 |  450.00
--  Aisha |      102 | 1200.00
--  Rahul |          |
--  Sara  |          |
--  Imran |          |
-- (5 rows)Code language: PHP (php)
```

All customers are back. Rahul now shows no order, because his only order (₹300) didn’t meet the condition. The rule of thumb: **conditions on the right table of a LEFT JOIN go in `ON`; conditions that should remove whole rows go in `WHERE`.** For INNER JOIN, both places give the same result.

### 14. Duplicate Rows Inflating Totals:

Remember that a join creates one row per matching pair. When you join a table to **two levels** of “many”, rows multiply, and sums silently go wrong:

```php
SELECT c.name, SUM(o.amount) AS wrong_total, COUNT(*)
FROM customers c
JOIN orders o       ON o.customer_id = c.id
JOIN order_items oi ON oi.order_id   = o.id
GROUP BY c.name
ORDER BY c.name;

--  name  | wrong_total | count
-- -------+-------------+-------
--  Aisha |     2100.00 |     3
--  Rahul |      300.00 |     1Code language: PHP (php)
```

Aisha really spent ₹1,650. But order 101 has **two** items, so after joining `order_items` it appears on two rows, and its ₹450 is counted twice: 450 + 450 + 1200 = 2100. This “fan-out” bug is very common in reports and dashboards.

The fix is to **aggregate the many-side first** in a subquery, so each order is one row before you join it:

```php
SELECT c.name, SUM(o.amount) AS total_spent, SUM(i.items) AS items_bought
FROM customers c
JOIN orders o ON o.customer_id = c.id
JOIN (
  SELECT order_id, SUM(qty) AS items
  FROM order_items
  GROUP BY order_id
) i ON i.order_id = o.id
GROUP BY c.name
ORDER BY c.name;

--  name  | total_spent | items_bought
-- -------+-------------+--------------
--  Aisha |     1650.00 |            4
--  Rahul |      300.00 |            1Code language: PHP (php)
```

Whenever a total looks too big, check whether a join has multiplied your rows. Comparing `COUNT(*)` before and after adding a join is a quick test.

### 15. Other Tips:

- **Always qualify column names** (`c.name`, `o.id`) when joining. If both tables have an `id` or `name` column, an unqualified name is either an error or a confusing bug.

- **USING** is a shortcut when both columns have the same name: `JOIN orders USING (customer_id)` instead of `ON a.customer_id = b.customer_id`. It also returns that column only once.

- **Avoid `NATURAL JOIN`.** It joins on every column with the same name automatically, so adding a column like `created_at` to both tables later silently changes the result.

- **Index your join columns.** Primary keys are indexed automatically, but foreign key columns like `orders.customer_id` usually aren’t. Without an index, the database may have to scan the whole table for every match. See our [indexing lesson](https://blog.khanwaseem.com/database-indexing/) for how to read `EXPLAIN` output.

- **Watch for `NULL` in join columns.** `NULL = NULL` is not true in SQL, so rows with a `NULL` join key never match anything.

## Conclusion:

Joins let you store data once, in well-organised tables, and still combine it whenever you need. **INNER JOIN** returns only matching pairs, **LEFT JOIN** keeps every row from the first table (and with `IS NULL` finds rows that have no match), **RIGHT JOIN** is its mirror, **FULL OUTER JOIN** keeps everything from both sides, **CROSS JOIN** creates every combination, and a **self join** connects a table to itself. We chained four tables, combined joins with `GROUP BY`, and fixed the two classic bugs: filtering a LEFT JOIN in `WHERE` instead of `ON`, and totals inflated by row fan-out.

In the next database lesson we will learn about **transactions and ACID**: how databases keep your data correct when many things happen at once, or when something fails halfway through.

### Related posts:

[Database Indexing: How Indexes Speed Up Queries](https://blog.khanwaseem.com/database-indexing/)
[What is MYSQL Database?](https://blog.khanwaseem.com/sql/)
[CSS – Table](https://blog.khanwaseem.com/css-table/)
[What Is Database Sharding? Partitioning Explained](https://blog.khanwaseem.com/what-is-database-sharding/)

Powered by [YARPP](https://yarpp.com).
