Explain it simply
What you will build
The sales team of an online shop wants to know every day how many orders each customer has placed and who has never ordered at all. In this project you build the report query that answers that question, starting from nothing.
There are three stages: first create two tables and sample data, then report the order count per customer, then add revenue and a date filter. At each stage, predict the result in your head before you run it; when the two differ, find out why.
Problem → Why → Solution
The problem: customers vanish from the report
The developer who wrote the first version used JOIN, which means INNER JOIN. The report shows Ana and Antonio and leaves out Alfreds and Around the Horn entirely, yet customers who have never ordered are exactly the ones the sales team wants to call. The query raised no error, so nobody noticed the report was wrong for two months.
SELECT c.customer_name, COUNT(*) AS total_orders
FROM customers AS c
JOIN orders AS o ON o.customer_id = c.customer_id -- INNER JOIN
GROUP BY c.customer_id, c.customer_name;
-- only customers WITH orders appear; the zero-order ones are missingWhy this happens
An INNER JOIN produces a row only when both tables have a match. A customer with no orders disappears at the join step and never reaches GROUP BY. A LEFT JOIN keeps every row of the left table, customers, and fills the order columns with NULL when there is no matching order.
Core concept: reasoning about a report in stages
A report can only be trusted if the data underneath is right, so the project starts with the schema. customers has customer_id as its primary key, so each customer is exactly one row. orders.customer_id is NOT NULL and a foreign key, so no order can exist without an owner. The CHECK (amount > 0) on amount keeps negative values from corrupting revenue totals, and storing money as numeric(10, 2) rather than a float avoids rounding errors when the amounts are summed.
To write report queries correctly, you need to know the order PostgreSQL works in. You write SELECT first, but the logical order is FROM/JOIN → WHERE → GROUP BY → HAVING → SELECT → ORDER BY. Each step sees only the result of the step before it.
LEFT JOIN keeps every customer
Ana has two orders, so she produces two rows; Antonio produces one. Alfreds and Around the Horn each produce one row whose order_id is NULL.
GROUP BY folds them to one row per customer
Grouping by customer_id matters, because two customers can share a name. Since customer_id is the primary key, PostgreSQL also lets you select customer_name and country.
COUNT(o.order_id) skips NULLs
COUNT(*) counts rows, so it reports 1 for a customer without orders. COUNT(o.order_id) counts only non-NULL values and gives the correct 0.
SUM skips NULLs too, but when a whole group is NULL it returns NULL rather than 0. To show 0 in the report, write COALESCE(SUM(o.amount), 0). With only total_orders DESC in ORDER BY, PostgreSQL does not guarantee the order of customers who tie, and it can change from run to run; that is why customer_name is added as a second sort key.
- Start from customers
- LEFT JOIN orders (filters in ON)
- GROUP BY customer_id
- COUNT/SUM, COALESCE the NULLs
- ORDER BY plus a tie-breaker
Ask first who must always appear in the report; that table belongs on the left side of the LEFT JOIN.
General pattern
SELECT parent.key_column,
parent.label_column,
COUNT(child.id_column) AS child_count,
COALESCE(SUM(child.amount), 0) AS child_total
FROM parent_table AS parent
LEFT JOIN child_table AS child
ON child.parent_key = parent.key_column
AND child_filter_condition
GROUP BY parent.key_column, parent.label_column
ORDER BY child_count DESC, parent.label_column;The parent table supplies the rows that must always appear, and the child table supplies the rows to count or sum. Keep filters on the child inside ON so no parent row is lost.
Worked example: schema, data and the first report
This single script is the foundation of the whole project. It creates two tables, inserts four customers and three orders, and runs the report query. You can run it from top to bottom on an empty PostgreSQL database. Before you run the report, predict the result: how many orders will Ana have?
CREATE TABLE customers (
customer_id integer PRIMARY KEY,
customer_name text NOT NULL,
country text NOT NULL
);
CREATE TABLE orders (
order_id integer PRIMARY KEY,
customer_id integer NOT NULL REFERENCES customers (customer_id),
order_date date NOT NULL,
amount numeric(10, 2) NOT NULL CHECK (amount > 0)
);
INSERT INTO customers VALUES
(1, 'Alfreds Futterkiste', 'Germany'),
(2, 'Ana Trujillo', 'Mexico'),
(3, 'Antonio Moreno', 'Mexico'),
(4, 'Around the Horn', 'UK');
INSERT INTO orders VALUES
(10, 2, '2026-01-15', 120.00),
(11, 3, '2026-02-03', 45.50),
(12, 2, '2026-03-08', 35.00);
SELECT c.customer_name,
c.country,
COUNT(o.order_id) AS total_orders
FROM customers AS c
LEFT JOIN orders AS o
ON o.customer_id = c.customer_id
GROUP BY c.customer_id, c.customer_name, c.country
ORDER BY total_orders DESC, c.customer_name;Code breakdown
- Rules protect the report
customer_id integer NOT NULL REFERENCES customers (customer_id),The foreign key stops orders for customers who do not exist, so every order in the report belongs to a real customer.
- Keep every customer
LEFT JOIN orders AS oWith customers on the left, Alfreds and Around the Horn survive the join with NULL order columns.
- Count real orders only
COUNT(o.order_id) AS total_ordersNULL order_ids are not counted, so customers without orders get 0; COUNT(*) would give them 1.
- Group by the key
GROUP BY c.customer_id, c.customer_name, c.countrycustomer_id identifies each customer exactly; listing the name and country as well keeps the query valid in standard SQL and every database.
- Deterministic order
ORDER BY total_orders DESC, c.customer_name;Puts the busiest customer first and breaks ties by name, so every run returns the same order.
customer_name | country | total_orders
--------------------+---------+-------------
Ana Trujillo | Mexico | 2
Antonio Moreno | Mexico | 1
Alfreds Futterkiste | Germany | 0
Around the Horn | UK | 0Stage 3: revenue and a date window
The sales team now wants order counts and revenue since 1 February, while still listing all four customers. Putting the date condition inside the ON clause makes the join skip only the January order and leaves the customer rows alone. The result is Antonio (1, 45.50), Ana (1, 35.00), Alfreds (0, 0) and Around the Horn (0, 0).
SELECT c.customer_name,
COUNT(o.order_id) AS orders_since_feb,
COALESCE(SUM(o.amount), 0) AS revenue_since_feb
FROM customers AS c
LEFT JOIN orders AS o
ON o.customer_id = c.customer_id
AND o.order_date >= DATE '2026-02-01'
GROUP BY c.customer_id, c.customer_name
ORDER BY revenue_since_feb DESC, c.customer_name;If you move it to WHERE
Writing WHERE o.order_date >= '2026-02-01' runs after the join, and the NULL order_date of order-less rows fails the condition. Alfreds and Around the Horn vanish, and so would any customer whose only order was in January. The LEFT JOIN has quietly become an INNER JOIN.
In real projects
This report in real projects
This pattern, a parent table LEFT JOINed to the child rows it counts, is the backbone of countless dashboards: reviews per product, students per teacher, sales per category. BI tools such as Metabase, Grafana or Looker Studio usually take exactly this kind of SQL and draw a chart from it.
- Saving the report as a view (CREATE VIEW customer_order_report AS ...) lets the dashboard and the API share one piece of logic.
- Once there are millions of rows, add an index on orders(customer_id, order_date) and check the plan with EXPLAIN ANALYZE; for very large data, use a materialized view refreshed every night.
- When the app supplies the date filter, send it as a parameterised value ($1) from the previous lesson instead of gluing the date string into the SQL.
Common mistakes
Common mistakes in this report
Pairing LEFT JOIN with COUNT(*)
Every customer without orders still has one NULL row, so COUNT(*) reports 1 and the report claims everyone has ordered at least once. Count a NOT NULL column of the child table, such as its primary key.
Forgetting that the join multiplies rows
When counting customers per country, Ana becomes two rows after the join, so COUNT(c.customer_id) reports 3 for Mexico. To count each customer once after a join, use COUNT(DISTINCT c.customer_id).
ORDER BY without a tie-breaker
With only ORDER BY total_orders DESC, the order of the two customers with 0 is undefined. Tests pass one run and fail the next, and paginated pages can repeat or skip rows.
Best practices
Best practices
- Work out the expected result by hand on the sample data before running the query; when it differs from your prediction, check your understanding before the query.
- Put a customer with no orders, a customer with several orders and a date right on the filter boundary into the test data on purpose.
- Give tables short aliases such as c and o and prefix every column with one, so it is obvious which table each value comes from.
Mini challenge
Mini challenge: a country summary
Management wants one row per country with the number of customers, the number of orders and the total revenue. Countries without orders must still appear with 0. Use the schema and data from above.
- Use customers as the base table and LEFT JOIN orders
- Count each customer only once with COUNT(DISTINCT ...)
- Show revenue as 0, not NULL, when there are no orders
- Sort by revenue, highest first, and break ties by country name
SELECT c.country,
-- TODO: number of distinct customers
-- TODO: number of orders (customers without orders count 0)
-- TODO: total revenue, 0 instead of NULL
FROM customers AS c
-- TODO: join orders so that every customer is kept
-- TODO: one row per country
-- TODO: highest revenue first, ties by country
;Expected: Three rows: Mexico (customers 2, orders 3, revenue 200.50), Germany (1, 0, 0) and UK (1, 0, 0).
Show hint
Mexico has two customers and three orders. If COUNT(c.customer_id) shows 3, DISTINCT is still missing. For revenue, use COALESCE(SUM(o.amount), 0).
Show solution
SELECT c.country,
COUNT(DISTINCT c.customer_id) AS customers,
COUNT(o.order_id) AS orders,
COALESCE(SUM(o.amount), 0) AS revenue
FROM customers AS c
LEFT JOIN orders AS o
ON o.customer_id = c.customer_id
GROUP BY c.country
ORDER BY revenue DESC, c.country;Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Put the table whose rows must always appear on the left of the LEFT JOIN.
- COUNT(child.id) skips NULLs and gives 0, while COUNT(*) gives 1.
- Keep filters on the child table inside ON; in WHERE they turn the LEFT JOIN into an INNER JOIN.
- COALESCE(SUM(...), 0), COUNT(DISTINCT ...) and an ORDER BY with a tie-breaker make a report correct and stable.
PostgreSQL SQL Tutorial — PostgreSQL Global Development Group