SQL Interview Questions and Answers Part 2 - Joins in Real-Time Scenarios

SQL Interview Q&A · Part 2 of 10

In this post we are going to cover joins in real-time scenarios: INNER, LEFT and FULL OUTER JOIN, anti joins, self joins, CROSS JOIN, and what happens to the row count when you join. These are 7 real SQL interview questions, asked the way they come up on the job, and the last one is a scenario where revenue goes up after a join and Finance wants to know why.

Joins are in almost every SQL interview, and not because the syntax is hard. The interviewer wants to know if you understand what a join does to your rows: which rows it keeps, which it drops, and when it quietly multiplies them. That is where real reports go wrong.

Every query below is complete, so you can copy it, run it on the sample data and get exactly the output shown under it.

Part 2 of the SQL Server RealTime Questions Answers series on TechBrothersIT.

The short answer

Say this first

A join returns one row per matching pair, so the grain of the result depends on the keys. INNER keeps matches, LEFT keeps every left row, FULL keeps both sides. Filters on the right table of a LEFT JOIN belong in ON, and a one-to-many join multiplies amounts unless you aggregate first or use EXISTS.

Keep the word grain in mind. Most of the questions below are about it.

Let's create some sample data

We use a small shop database called TB Shop: departments, employees, customers, products, orders, order items and payments, plus a small calendar_months table that we use in question 6. The script is written for PostgreSQL, and it runs on SQL Server, MySQL 8 or Snowflake with very small changes.

Sample data - SQL script (PostgreSQL)
DROP TABLE IF EXISTS payments;
DROP TABLE IF EXISTS order_items;
DROP TABLE IF EXISTS orders;
DROP TABLE IF EXISTS products;
DROP TABLE IF EXISTS customers;
DROP TABLE IF EXISTS employees;
DROP TABLE IF EXISTS departments;

CREATE TABLE departments (dept_id INT PRIMARY KEY, dept_name VARCHAR(20));
INSERT INTO departments VALUES (10, 'Sales'), (20, 'Engineering'), (30, 'HR'), (40, 'Finance');

CREATE TABLE employees (
  emp_id     INT PRIMARY KEY,
  name       VARCHAR(20),
  dept_id    INT,            -- NULL = not assigned yet
  manager_id INT,            -- NULL = top of the company
  salary     INT,
  hire_date  DATE
);
INSERT INTO employees VALUES
  (1, 'Aisha',  NULL, NULL, 150000, '2018-03-01'),
  (2, 'Omar',   20,   1,    120000, '2019-06-15'),
  (3, 'Lina',   20,   2,     90000, '2021-01-10'),
  (4, 'Ravi',   20,   2,     90000, '2022-04-05'),
  (5, 'Mei',    20,   2,     75000, '2024-09-01'),
  (6, 'Sara',   10,   1,     95000, '2020-02-20'),
  (7, 'Daniel', 10,   6,    105000, '2021-07-01'),
  (8, 'Fatima', 10,   6,     60000, '2023-11-12'),
  (9, 'John',   30,   1,     70000, '2019-09-30'),
  (10,'Zara',   NULL, 9,     55000, '2026-01-05');

CREATE TABLE customers (
  customer_id INT PRIMARY KEY,
  name        VARCHAR(20),
  city        VARCHAR(20),
  region      VARCHAR(10),    -- NULL = unknown
  email       VARCHAR(40)
);
INSERT INTO customers VALUES
  (1, 'Sara Khan',  'Toronto', 'East', 'sara@mail.com'),
  (2, 'Omar Ali',   'Dallas',  'West', 'omar@mail.com'),
  (3, 'Lina Park',  'Seattle', 'West', 'lina@mail.com'),
  (4, 'Mei Chen',   'Boston',  'East', 'mei@mail.com'),
  (5, 'Ravi Patel', 'Austin',  NULL,   'ravi@mail.com'),
  (6, 'Chen Wu',    'Denver',  'West', 'chen@mail.com'),
  (7, 'Sara K.',    'Toronto', 'East', 'sara@mail.com');

CREATE TABLE products (product_id INT PRIMARY KEY, product VARCHAR(20), category VARCHAR(15), price DECIMAL(10,2));
INSERT INTO products VALUES
  (1, 'Laptop',   'Electronics', 1200.00),
  (2, 'Monitor',  'Electronics',  300.00),
  (3, 'Keyboard', 'Accessories',   50.00),
  (4, 'Mouse',    'Accessories',   25.00),
  (5, 'Desk',     'Furniture',    400.00),
  (6, 'Chair',    'Furniture',    250.00);

CREATE TABLE orders (
  order_id    INT PRIMARY KEY,
  customer_id INT,
  order_date  DATE,
  status      VARCHAR(10),
  amount      DECIMAL(10,2)
);
INSERT INTO orders VALUES
  (1001, 1, '2026-01-05', 'Delivered', 1250.00),
  (1002, 2, '2026-01-18', 'Delivered',  300.00),
  (1003, 4, '2026-02-02', 'Delivered',  650.00),
  (1004, 1, '2026-02-14', 'Cancelled',   50.00),
  (1005, 3, '2026-02-20', 'Delivered', 1200.00),
  (1006, 4, '2026-03-03', 'Shipped',    275.00),
  (1007, 5, '2026-03-15', 'Delivered',  400.00),
  (1008, 2, '2026-04-01', 'Delivered',   75.00),
  (1009, 4, '2026-04-22', 'Delivered',  250.00),
  (1010, 1, '2026-05-09', 'Shipped',    300.00),
  (1011, 3, '2026-05-30', 'Cancelled',  400.00),
  (1012, 7, '2026-06-11', 'Delivered',   50.00);

CREATE TABLE order_items (order_id INT, product_id INT, qty INT, unit_price DECIMAL(10,2));
INSERT INTO order_items VALUES
  (1001, 1, 1, 1200.00), (1001, 3, 1, 50.00),
  (1002, 2, 1, 300.00),
  (1003, 5, 1, 400.00), (1003, 6, 1, 250.00),
  (1004, 3, 1, 50.00),
  (1005, 1, 1, 1200.00),
  (1006, 6, 1, 250.00), (1006, 4, 1, 25.00),
  (1007, 5, 1, 400.00),
  (1008, 4, 3, 25.00),
  (1009, 6, 1, 250.00),
  (1010, 2, 1, 300.00),
  (1011, 5, 1, 400.00),
  (1012, 3, 1, 50.00);

CREATE TABLE payments (payment_id INT PRIMARY KEY, order_id INT, paid_amount DECIMAL(10,2));
INSERT INTO payments VALUES
  (1, 1001, 1250.00), (2, 1002, 300.00), (3, 1003, 400.00), (4, 1003, 250.00), (5, 1005, 1200.00);

DROP TABLE IF EXISTS calendar_months;
-- the reporting calendar (in a real warehouse: the date dimension)
CREATE TABLE calendar_months (month_start DATE PRIMARY KEY, month_end DATE, month_name VARCHAR(10));
INSERT INTO calendar_months VALUES
  ('2026-01-01', '2026-01-31', 'Jan'),
  ('2026-02-01', '2026-02-28', 'Feb'),
  ('2026-03-01', '2026-03-31', 'Mar');

Here are the employees. Notice that Aisha and Zara have no department, and nobody works in department 40, Finance. Also notice that Daniel earns 105000, more than his manager Sara with 95000.

employees10 rows
emp_idnamedept_idmanager_idsalaryhire_date
1AishaNULLNULL1500002018-03-01
2Omar2011200002019-06-15
3Lina202900002021-01-10
4Ravi202900002022-04-05
5Mei202750002024-09-01
6Sara101950002020-02-20
7Daniel1061050002021-07-01
8Fatima106600002023-11-12
9John301700002019-09-30
10ZaraNULL9550002026-01-05

And here are the payments. Order 1003 was paid in two parts, 400.00 and 250.00. That one order is the whole story of the scenario.

payments5 rows
payment_idorder_idpaid_amount
110011250.00
21002300.00
31003400.00
41003250.00
510051200.00

Question 1: HR wants every department with its employees, including the department with nobody in it and the employees with no department yet. What is the difference between INNER JOIN, LEFT JOIN and FULL OUTER JOIN, and which one gives this list?

An INNER JOIN returns only the rows that match on both sides. A LEFT JOIN returns every row from the left table, plus the matches, with NULLs where there is no match. A FULL OUTER JOIN returns every row from both tables, matched where possible. HR's list needs the FULL OUTER JOIN.

Let's join departments to employees all three ways and count the rows.

SQL - Row counts: INNER vs LEFT vs FULL OUTER JOIN
SELECT 'INNER' AS join_type, COUNT(*) AS row_count
FROM departments d
INNER JOIN employees e ON e.dept_id = d.dept_id
UNION ALL
SELECT 'LEFT', COUNT(*)
FROM departments d
LEFT JOIN employees e ON e.dept_id = d.dept_id
UNION ALL
SELECT 'FULL OUTER', COUNT(*)
FROM departments d
FULL OUTER JOIN employees e ON e.dept_id = d.dept_id
ORDER BY row_count;
Output (PostgreSQL 16)3 rows
join_typerow_count
INNER8
LEFT9
FULL OUTER11

The INNER JOIN returns 8 rows. The LEFT JOIN returns 9, because Finance has no employees but is still kept. The FULL OUTER JOIN returns 11. Now let's look at the full outer join itself.

SQL - FULL OUTER JOIN: unmatched rows from both sides
SELECT d.dept_name, e.name AS employee
FROM departments d
FULL OUTER JOIN employees e ON e.dept_id = d.dept_id
ORDER BY d.dept_name, e.name;
Output (PostgreSQL 16)11 rows
dept_nameemployee
EngineeringLina
EngineeringMei
EngineeringOmar
EngineeringRavi
FinanceNULL
HRJohn
SalesDaniel
SalesFatima
SalesSara
NULLAisha
NULLZara

Finance appears with a NULL employee: that is the row the LEFT JOIN added. Aisha and Zara appear with a NULL department, because they have no department assigned. Only a full outer join keeps both kinds of unmatched rows. PostgreSQL sorts the NULL departments last, SQL Server sorts them first.

A RIGHT JOIN is just a LEFT JOIN with the tables swapped, so most teams always write LEFT.

MySQL

There is no FULL OUTER JOIN in MySQL. You emulate it with a LEFT JOIN, a UNION, and a RIGHT JOIN.

Question 2: Marketing wants to email the customers who have never placed an order. How do you find them in SQL?

This is called an anti join: keep the rows from one table that have no match in the other. The classic way is a LEFT JOIN from customers to orders, keeping only the rows where the order side is NULL.

SQL - Customers who never ordered: LEFT JOIN ... IS NULL
SELECT c.customer_id, c.name
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id
WHERE o.order_id IS NULL
ORDER BY c.customer_id;
Output (PostgreSQL 16)1 row
customer_idname
6Chen Wu

Customer 6, Chen Wu, has never ordered. The second way is NOT EXISTS: keep each customer for whom no order exists.

SQL - Customers who never ordered: NOT EXISTS
SELECT c.customer_id, c.name
FROM customers c
WHERE NOT EXISTS (SELECT 1 FROM orders o
                  WHERE o.customer_id = c.customer_id)
ORDER BY c.customer_id;
Output (PostgreSQL 16)1 row
customer_idname
6Chen Wu

Same answer, Chen Wu, and it reads much closer to the business question. A few details interviewers check:

  • Test the key. In the LEFT JOIN version, test a column that can never be NULL in the right table, like its primary key, o.order_id.
  • Avoid NOT IN against a subquery that can return a NULL. One NULL in the list, and you get no rows at all. We cover that trap in part 4 of this series.
  • NOT EXISTS has clear intent and can never duplicate customers.

In a real project, I prefer NOT EXISTS here, and most optimizers turn it into the same anti join plan anyway.

Question 3: You joined 7 customers to their orders and got 13 rows back. Why did the row count go up, and when does it become a bug?

Because the join is one to many. A join returns one row for every matching pair, so a customer with three orders becomes three rows.

SQL - Seven customers become thirteen rows
SELECT (SELECT COUNT(*) FROM customers) AS customers,
       COUNT(*) AS rows_after_join
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id;
Output (PostgreSQL 16)1 row
customersrows_after_join
713

We start with 7 customers, and after the join to orders we have 13 rows. Let's break it down by customer to see where the extra rows come from.

SQL - Where the extra rows come from
SELECT c.customer_id, c.name, COUNT(*) AS rows_after_join
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id
GROUP BY c.customer_id, c.name
ORDER BY c.customer_id;
Output (PostgreSQL 16)7 rows
customer_idnamerows_after_join
1Sara Khan3
2Omar Ali2
3Lina Park2
4Mei Chen3
5Ravi Patel1
6Chen Wu1
7Sara K.1

Sara Khan and Mei Chen have 3 rows each, Omar Ali and Lina Park have 2. Chen Wu has no orders, but the LEFT JOIN still keeps one row for him.

That is not a bug, it is the grain changing: one row per order, not one row per customer. The bug comes when you then sum a customer-level column, like a credit limit, and count it three times for Sara Khan.

Before any join

Ask two questions: what is the key of each table, and what will the grain of the result be? Check that the right side is unique on the join key with GROUP BY and HAVING COUNT(*) > 1, and if it isn't, aggregate it first.

Question 4: A manager wants every customer with their shipped orders, if they have any, but your LEFT JOIN returns only 2 customers. What is the difference between putting the filter in ON and in WHERE?

WHERE runs after the join, so a WHERE condition on the right table throws away the unmatched rows. The ON condition is part of the matching, so it keeps them. Let's put o.status = 'Shipped' in WHERE first.

SQL - Filter in WHERE: the LEFT JOIN becomes an INNER JOIN
SELECT c.name, o.order_id, o.status
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id
WHERE o.status = 'Shipped'
ORDER BY c.customer_id;
Output (PostgreSQL 16)2 rows
nameorder_idstatus
Sara Khan1010Shipped
Mei Chen1006Shipped

Just two rows: Sara Khan with order 1010 and Mei Chen with order 1006. Every other customer disappeared. For customers without a shipped order the order columns are NULL, and NULL equals Shipped is not true, so WHERE removes them. The LEFT JOIN quietly became an INNER JOIN.

Now move the condition into the ON clause.

SQL - Filter in ON: every customer is kept
SELECT c.name, o.order_id, o.status
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id
                  AND o.status = 'Shipped'
ORDER BY c.customer_id;
Output (PostgreSQL 16)7 rows
nameorder_idstatus
Sara Khan1010Shipped
Omar AliNULLNULL
Lina ParkNULLNULL
Mei Chen1006Shipped
Ravi PatelNULLNULL
Chen WuNULLNULL
Sara K.NULLNULL

All seven customers are kept, and only the shipped orders are attached. The rest simply show NULL in order_id and status.

The rule to remember: filters on the right table of a LEFT JOIN go in ON, filters on the left table go in WHERE. The one deliberate exception is WHERE o.order_id IS NULL, the anti join from question 2.

Question 5: HR asks for each employee with their manager's name, and then for the employees who earn more than their manager. How do you write both queries?

The manager is just another row in the same employees table, so we join the table to itself with two aliases: e for the employee and m for the manager, matching the employee's manager_id to the manager's emp_id. We use a LEFT JOIN, so the top of the company is kept.

SQL - Self join: each employee with their manager
SELECT e.name AS employee, m.name AS manager
FROM employees e
LEFT JOIN employees m ON m.emp_id = e.manager_id
ORDER BY e.emp_id;
Output (PostgreSQL 16)10 rows
employeemanager
AishaNULL
OmarAisha
LinaOmar
RaviOmar
MeiOmar
SaraAisha
DanielSara
FatimaSara
JohnAisha
ZaraJohn

Aisha is the CEO, so her manager is NULL. An inner join would silently drop her from the org chart.

Now the second question. Same self join, plus one condition: the employee's salary is greater than the manager's salary.

SQL - Employees who earn more than their manager
SELECT e.name AS employee, e.salary,
       m.name AS manager, m.salary AS manager_salary
FROM employees e
JOIN employees m ON m.emp_id = e.manager_id
WHERE e.salary > m.salary
ORDER BY e.emp_id;
Output (PostgreSQL 16)1 row
employeesalarymanagermanager_salary
Daniel105000Sara95000

Daniel earns 105000, and his manager Sara earns 95000. Here an inner join is the right choice, because an employee without a manager has nobody to compare with.

Tip

Always pick the join type by asking one question: should the unmatched rows stay, or go?

Question 6: The monthly sales report skips months with no sales for a category, so the chart has gaps. How do you build a full category by month grid that shows 0 for empty months?

A GROUP BY can only return groups that exist in the data. If nobody bought accessories in February, there is no February row to show. So first we build the complete grid with a CROSS JOIN: every category, times every month.

The month list comes from a small calendar table. In a real warehouse that is your date dimension, or you generate it with a recursive CTE.

calendar_months3 rows
month_startmonth_endmonth_name
2026-01-012026-01-31Jan
2026-02-012026-02-28Feb
2026-03-012026-03-31Mar

Here is the plan: the CTE gets the sales lines without cancelled orders, the CROSS JOIN builds the grid, the LEFT JOIN attaches the sales, and COALESCE turns the empty cells into 0.

SQL - CROSS JOIN the grid, LEFT JOIN the sales, COALESCE to 0
WITH sales AS (
  SELECT p.category, o.order_date, oi.qty * oi.unit_price AS amount
  FROM orders o
  JOIN order_items oi ON oi.order_id = o.order_id
  JOIN products p     ON p.product_id = oi.product_id
  WHERE o.status <> 'Cancelled')
SELECT c.category, m.month_name,
       COALESCE(SUM(s.amount), 0.00) AS sales
FROM (SELECT DISTINCT category FROM products) c
CROSS JOIN calendar_months m
LEFT JOIN sales s ON s.category = c.category
     AND s.order_date BETWEEN m.month_start AND m.month_end
GROUP BY c.category, m.month_name, m.month_start
ORDER BY c.category, m.month_start;
Output (PostgreSQL 16)9 rows
categorymonth_namesales
AccessoriesJan50.00
AccessoriesFeb0.00
AccessoriesMar25.00
ElectronicsJan1500.00
ElectronicsFeb1200.00
ElectronicsMar0.00
FurnitureJan0.00
FurnitureFeb650.00
FurnitureMar650.00

Three categories times three months gives 9 rows. Accessories in February is 0.00, because its only order that month was cancelled. Electronics in March and Furniture in January are 0.00 too, so the chart has no gaps.

Be careful with CROSS JOIN on big tables. The row count is the product of both sides, so two large tables can explode into an enormous result. Cross join small lists, like categories and months, never two fact tables.

Scenario 7: Finance says revenue went up after you joined orders to payments: 4,050 instead of 3,400. Why did it happen, and how do you fix it?

Finance says paid revenue is 3400.00, and your report after the join says 4050.00. Let's look at the rows first.

SQL - The fan-out: order 1003 matches two payments
SELECT o.order_id, o.amount, p.payment_id, p.paid_amount
FROM orders o
JOIN payments p ON p.order_id = o.order_id
ORDER BY o.order_id, p.payment_id;
Output (PostgreSQL 16)5 rows
order_idamountpayment_idpaid_amount
10011250.0011250.00
1002300.002300.00
1003650.003400.00
1003650.004250.00
10051200.0051200.00

Order 1003 was paid in two parts, payments 3 and 4, so the join returns it twice, and its amount of 650.00 is there twice. That is the fan-out. Now the totals:

SQL - The wrong total
SELECT SUM(o.amount) AS revenue, SUM(p.paid_amount) AS paid
FROM orders o
JOIN payments p ON p.order_id = o.order_id;
Output (PostgreSQL 16)1 row
revenuepaid
4050.003400.00

Revenue is 4050.00, because the 650.00 is counted twice. But the paid column is still right, 3400.00, because the result is now one row per payment, not per order.

The fix: aggregate payments to one row per order before you join.

SQL - Fix: aggregate payments per order, then join
WITH paid AS (
  SELECT order_id, SUM(paid_amount) AS paid
  FROM payments
  GROUP BY order_id)
SELECT SUM(o.amount) AS revenue, SUM(paid.paid) AS paid
FROM orders o
JOIN paid ON paid.order_id = o.order_id;
Output (PostgreSQL 16)1 row
revenuepaid
3400.003400.00

Now each order matches exactly one row, and both totals are 3400.00. And if you only need to know whether an order was paid, use EXISTS. It checks for a match without multiplying rows.

SQL - Or: EXISTS when you only need to know it was paid
SELECT SUM(o.amount) AS revenue
FROM orders o
WHERE EXISTS (SELECT 1 FROM payments p
              WHERE p.order_id = o.order_id);
Output (PostgreSQL 16)1 row
revenue
3400.00

Same 3400.00.

  • In the interview, say the cause in one sentence: the join changed the grain.
  • Then say how you would catch it: compare row counts and totals before and after every join.

Key points to remember

  • INNER keeps matches, LEFT keeps every left row, FULL keeps both sides
  • Anti join: LEFT JOIN ... IS NULL or NOT EXISTS (avoid NOT IN)
  • A one-to-many join changes the grain and multiplies rows
  • LEFT JOIN: right-table filters go in ON, not WHERE
  • Aggregate before joining, or use EXISTS, to stop fan-out

The full SQL script

Here is everything in one script: the sample data and every query from this post, in order. Copy it and run it top to bottom.

Show the full SQL script (sample data and every query)
Full script - copy and run top to bottom
-- ========================================================================
-- SQL Interview Q&A #2 - Joins in real-time scenarios
-- TechBrothersIT. Sample data is invented for teaching.
-- Standard SQL, tested on PostgreSQL 16 (and cross-checked on DuckDB). Runs top to bottom in one go.
-- Run it in an empty database or schema: other videos reuse table names
-- like dim_customer, and their leftover tables can block the DROPs below.
-- PostgreSQL example:  CREATE SCHEMA sql_q02;  SET search_path TO sql_q02;
-- ========================================================================

-- Step 0: create and load the sample data
DROP TABLE IF EXISTS payments;
DROP TABLE IF EXISTS order_items;
DROP TABLE IF EXISTS orders;
DROP TABLE IF EXISTS products;
DROP TABLE IF EXISTS customers;
DROP TABLE IF EXISTS employees;
DROP TABLE IF EXISTS departments;

CREATE TABLE departments (dept_id INT PRIMARY KEY, dept_name VARCHAR(20));
INSERT INTO departments VALUES (10, 'Sales'), (20, 'Engineering'), (30, 'HR'), (40, 'Finance');

CREATE TABLE employees (
  emp_id     INT PRIMARY KEY,
  name       VARCHAR(20),
  dept_id    INT,            -- NULL = not assigned yet
  manager_id INT,            -- NULL = top of the company
  salary     INT,
  hire_date  DATE
);
INSERT INTO employees VALUES
  (1, 'Aisha',  NULL, NULL, 150000, '2018-03-01'),
  (2, 'Omar',   20,   1,    120000, '2019-06-15'),
  (3, 'Lina',   20,   2,     90000, '2021-01-10'),
  (4, 'Ravi',   20,   2,     90000, '2022-04-05'),
  (5, 'Mei',    20,   2,     75000, '2024-09-01'),
  (6, 'Sara',   10,   1,     95000, '2020-02-20'),
  (7, 'Daniel', 10,   6,    105000, '2021-07-01'),
  (8, 'Fatima', 10,   6,     60000, '2023-11-12'),
  (9, 'John',   30,   1,     70000, '2019-09-30'),
  (10,'Zara',   NULL, 9,     55000, '2026-01-05');

CREATE TABLE customers (
  customer_id INT PRIMARY KEY,
  name        VARCHAR(20),
  city        VARCHAR(20),
  region      VARCHAR(10),    -- NULL = unknown
  email       VARCHAR(40)
);
INSERT INTO customers VALUES
  (1, 'Sara Khan',  'Toronto', 'East', 'sara@mail.com'),
  (2, 'Omar Ali',   'Dallas',  'West', 'omar@mail.com'),
  (3, 'Lina Park',  'Seattle', 'West', 'lina@mail.com'),
  (4, 'Mei Chen',   'Boston',  'East', 'mei@mail.com'),
  (5, 'Ravi Patel', 'Austin',  NULL,   'ravi@mail.com'),
  (6, 'Chen Wu',    'Denver',  'West', 'chen@mail.com'),
  (7, 'Sara K.',    'Toronto', 'East', 'sara@mail.com');

CREATE TABLE products (product_id INT PRIMARY KEY, product VARCHAR(20), category VARCHAR(15), price DECIMAL(10,2));
INSERT INTO products VALUES
  (1, 'Laptop',   'Electronics', 1200.00),
  (2, 'Monitor',  'Electronics',  300.00),
  (3, 'Keyboard', 'Accessories',   50.00),
  (4, 'Mouse',    'Accessories',   25.00),
  (5, 'Desk',     'Furniture',    400.00),
  (6, 'Chair',    'Furniture',    250.00);

CREATE TABLE orders (
  order_id    INT PRIMARY KEY,
  customer_id INT,
  order_date  DATE,
  status      VARCHAR(10),
  amount      DECIMAL(10,2)
);
INSERT INTO orders VALUES
  (1001, 1, '2026-01-05', 'Delivered', 1250.00),
  (1002, 2, '2026-01-18', 'Delivered',  300.00),
  (1003, 4, '2026-02-02', 'Delivered',  650.00),
  (1004, 1, '2026-02-14', 'Cancelled',   50.00),
  (1005, 3, '2026-02-20', 'Delivered', 1200.00),
  (1006, 4, '2026-03-03', 'Shipped',    275.00),
  (1007, 5, '2026-03-15', 'Delivered',  400.00),
  (1008, 2, '2026-04-01', 'Delivered',   75.00),
  (1009, 4, '2026-04-22', 'Delivered',  250.00),
  (1010, 1, '2026-05-09', 'Shipped',    300.00),
  (1011, 3, '2026-05-30', 'Cancelled',  400.00),
  (1012, 7, '2026-06-11', 'Delivered',   50.00);

CREATE TABLE order_items (order_id INT, product_id INT, qty INT, unit_price DECIMAL(10,2));
INSERT INTO order_items VALUES
  (1001, 1, 1, 1200.00), (1001, 3, 1, 50.00),
  (1002, 2, 1, 300.00),
  (1003, 5, 1, 400.00), (1003, 6, 1, 250.00),
  (1004, 3, 1, 50.00),
  (1005, 1, 1, 1200.00),
  (1006, 6, 1, 250.00), (1006, 4, 1, 25.00),
  (1007, 5, 1, 400.00),
  (1008, 4, 3, 25.00),
  (1009, 6, 1, 250.00),
  (1010, 2, 1, 300.00),
  (1011, 5, 1, 400.00),
  (1012, 3, 1, 50.00);

CREATE TABLE payments (payment_id INT PRIMARY KEY, order_id INT, paid_amount DECIMAL(10,2));
INSERT INTO payments VALUES
  (1, 1001, 1250.00), (2, 1002, 300.00), (3, 1003, 400.00), (4, 1003, 250.00), (5, 1005, 1200.00);

DROP TABLE IF EXISTS calendar_months;
-- the reporting calendar (in a real warehouse: the date dimension)
CREATE TABLE calendar_months (month_start DATE PRIMARY KEY, month_end DATE, month_name VARCHAR(10));
INSERT INTO calendar_months VALUES
  ('2026-01-01', '2026-01-31', 'Jan'),
  ('2026-02-01', '2026-02-28', 'Feb'),
  ('2026-03-01', '2026-03-31', 'Mar');


-- Step 1: Row counts: INNER vs LEFT vs FULL OUTER JOIN
SELECT 'INNER' AS join_type, COUNT(*) AS row_count
FROM departments d
INNER JOIN employees e ON e.dept_id = d.dept_id
UNION ALL
SELECT 'LEFT', COUNT(*)
FROM departments d
LEFT JOIN employees e ON e.dept_id = d.dept_id
UNION ALL
SELECT 'FULL OUTER', COUNT(*)
FROM departments d
FULL OUTER JOIN employees e ON e.dept_id = d.dept_id
ORDER BY row_count;

-- Step 2: FULL OUTER JOIN: unmatched rows from both sides
SELECT d.dept_name, e.name AS employee
FROM departments d
FULL OUTER JOIN employees e ON e.dept_id = d.dept_id
ORDER BY d.dept_name, e.name;

-- Step 3: Customers who never ordered: LEFT JOIN ... IS NULL
SELECT c.customer_id, c.name
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id
WHERE o.order_id IS NULL
ORDER BY c.customer_id;

-- Step 4: Customers who never ordered: NOT EXISTS
SELECT c.customer_id, c.name
FROM customers c
WHERE NOT EXISTS (SELECT 1 FROM orders o
                  WHERE o.customer_id = c.customer_id)
ORDER BY c.customer_id;

-- Step 5: Seven customers become thirteen rows
SELECT (SELECT COUNT(*) FROM customers) AS customers,
       COUNT(*) AS rows_after_join
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id;

-- Step 6: Where the extra rows come from
SELECT c.customer_id, c.name, COUNT(*) AS rows_after_join
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id
GROUP BY c.customer_id, c.name
ORDER BY c.customer_id;

-- Step 7: Filter in WHERE: the LEFT JOIN becomes an INNER JOIN
SELECT c.name, o.order_id, o.status
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id
WHERE o.status = 'Shipped'
ORDER BY c.customer_id;

-- Step 8: Filter in ON: every customer is kept
SELECT c.name, o.order_id, o.status
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id
                  AND o.status = 'Shipped'
ORDER BY c.customer_id;

-- Step 9: Self join: each employee with their manager
SELECT e.name AS employee, m.name AS manager
FROM employees e
LEFT JOIN employees m ON m.emp_id = e.manager_id
ORDER BY e.emp_id;

-- Step 10: Employees who earn more than their manager
SELECT e.name AS employee, e.salary,
       m.name AS manager, m.salary AS manager_salary
FROM employees e
JOIN employees m ON m.emp_id = e.manager_id
WHERE e.salary > m.salary
ORDER BY e.emp_id;

-- Step 11: CROSS JOIN the grid, LEFT JOIN the sales, COALESCE to 0
WITH sales AS (
  SELECT p.category, o.order_date, oi.qty * oi.unit_price AS amount
  FROM orders o
  JOIN order_items oi ON oi.order_id = o.order_id
  JOIN products p     ON p.product_id = oi.product_id
  WHERE o.status <> 'Cancelled')
SELECT c.category, m.month_name,
       COALESCE(SUM(s.amount), 0.00) AS sales
FROM (SELECT DISTINCT category FROM products) c
CROSS JOIN calendar_months m
LEFT JOIN sales s ON s.category = c.category
     AND s.order_date BETWEEN m.month_start AND m.month_end
GROUP BY c.category, m.month_name, m.month_start
ORDER BY c.category, m.month_start;

-- Step 12: The fan-out: order 1003 matches two payments
SELECT o.order_id, o.amount, p.payment_id, p.paid_amount
FROM orders o
JOIN payments p ON p.order_id = o.order_id
ORDER BY o.order_id, p.payment_id;

-- Step 13: The wrong total
SELECT SUM(o.amount) AS revenue, SUM(p.paid_amount) AS paid
FROM orders o
JOIN payments p ON p.order_id = o.order_id;

-- Step 14: Fix: aggregate payments per order, then join
WITH paid AS (
  SELECT order_id, SUM(paid_amount) AS paid
  FROM payments
  GROUP BY order_id)
SELECT SUM(o.amount) AS revenue, SUM(paid.paid) AS paid
FROM orders o
JOIN paid ON paid.order_id = o.order_id;

-- Step 15: Or: EXISTS when you only need to know it was paid
SELECT SUM(o.amount) AS revenue
FROM orders o
WHERE EXISTS (SELECT 1 FROM payments p
              WHERE p.order_id = o.order_id);
Next in this series

Part 3: GROUP BY and Aggregation

The sample data on this page is invented for teaching. Every output table is the real result of the query above it, run on PostgreSQL 16 over that sample data, and the portable queries were also checked on a second engine. Where SQL Server syntax is different, the post says so.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.