NIT ICT LESSON · SQL · BEGINNER TO PRACTICAL
SQL JOINs Explained: Build a Sales Report Step by Step
Learn INNER, LEFT, RIGHT and FULL OUTER JOINs using four linked sales tables. Run each query, see the result, find wrong totals and verify a five-day report.
Imagine you are reviewing five days of transactions (1–5 October 2026) for a fictional Kenyan retailer. The manager asks three questions: Who purchased? Which products sold? and What is the sales value of the completed orders? Those answers are stored across different tables. By the end of this lesson, you will join them, check the row counts, and explain a KSh 7,900 completed-sales result.
This is a five-day sales snapshot, not a calendar-week report: 1–5 October crosses an ISO-week boundary. Here, “sales value” means the sum of recorded order-line prices for completed orders; it is not a statement about cash collected, tax, refunds or profit. All sales-reporting queries below explicitly restrict the reporting window to 1 October inclusive through 6 October exclusive, so they keep the same meaning if the sample database later grows.
Before you start: Know the basics of SELECT, FROM and WHERE. If relational tables are new to you, begin with NIT’s database fundamentals guide or SQL for Data Analysis introduction.
What Is a SQL JOIN and Why Does It Matter?
A JOIN pairs rows from related tables according to an ON condition. A matching customer_id connects a customer record with each of their orders. A customer may place many orders; each order may contain several product lines. Instead of repeating every customer detail on every line, a relational database stores each kind of record separately and links it by an ID. The ON condition must express that genuine relationship: matching columns merely because they are both called id can silently remove rows or combine unrelated records. [1]
Primary key
A value that uniquely identifies a record: customers.customer_id identifies one customer.
Foreign key
A reference to another table: orders.customer_id points to a customer.
Row grain
The meaning of a single row. One row might represent an order—or a single product line within an order.
For example, if Amina places two orders, she appears once in customers but twice in orders. A JOIN correctly creates two joined rows. That is not automatically a duplicate-data error: the output has a different grain.
Beginner rule
First state what one output row should represent. Then choose the JOIN and aggregation that produce that grain. This single habit prevents many reporting mistakes. If an order has three line items, an order-to-item join produces three rows by design, even though there is only one order.
Meet the Sales Database: Four Connected Tables
This fictional training dataset uses Kenyan towns and prices in Kenyan shillings. It is designed for learning, not taken from real customers. The customers and products tables each contain five rows; there are six orders and nine order_items. Five orders are completed and one is cancelled.
Relationship map
customers (1) → (many) orders (1) → (many) order_items (many) ← (1) products. Match customer IDs, order IDs and product IDs—not names.
Table 1: customers — one row per customer
| customer_id | customer_name | city |
|---|---|---|
| 1 | Amina | Migori |
| 2 | Brian | Kisumu |
| 3 | Chao | Kisii |
| 4 | David | Nairobi |
| 5 | Esther | Homa Bay |
Table 2: orders — one row per order
| order_id | order_date | customer_id | status |
|---|---|---|---|
| 1001 | 2026-10-01 | 1 | completed |
| 1002 | 2026-10-01 | 2 | completed |
| 1003 | 2026-10-02 | 1 | completed |
| 1004 | 2026-10-03 | 3 | completed |
| 1005 | 2026-10-04 | 4 | cancelled |
| 1006 | 2026-10-05 | 2 | completed |
David placed a cancelled order; Esther placed no order at all. Those two situations are different, and the JOIN examples will preserve that distinction.
Table 3: products — one row per product
| product_id | product_name | list_price (KSh) |
|---|---|---|
| 101 | Notebook | 250 |
| 102 | Headset | 1,500 |
| 103 | Mouse | 900 |
| 104 | Flash Drive | 600 |
| 105 | Webcam | 2,500 |
Table 4: order_items — one row per order line
| order_id | product_id | quantity | unit_price (KSh) |
|---|---|---|---|
| 1001 | 101 | 2 | 250 |
| 1001 | 103 | 1 | 800 |
| 1002 | 102 | 1 | 1500 |
| 1002 | 104 | 2 | 600 |
| 1003 | 104 | 3 | 600 |
| 1004 | 101 | 1 | 250 |
| 1005 | 102 | 1 | 1500 |
| 1006 | 103 | 2 | 800 |
| 1006 | 101 | 1 | 250 |
The catalogue lists the Mouse at KSh 900, but the recorded sales price is KSh 800. Use order_items.unit_price for sales calculations—historic transactions must not be recomputed from a current catalogue price. Line value = quantity × unit_price.
Important reporting rule
Cancelled order 1005 contains KSh 1,500 in order lines but is excluded from completed-order sales value. A correct report must filter by order status before summing.
Set up the sample tables
Run the PostgreSQL setup below in a dedicated practice connection (for example, a local PostgreSQL client or a pgAdmin Query Tool session). It creates four temporary tables and loads exactly the rows shown here. Run the setup once, then keep the same connection for the examples: temporary tables vanish at session end, and rerunning the CREATE statements in the same session without dropping the tables raises an “already exists” error. Work in a dedicated training database/connection—not against production records. This is intentionally a small learning schema, not a full retail accounting system.
Open the full CREATE TABLE and INSERT setup SQL
Dialect note
The runnable examples use PostgreSQL SQL, including DATE ‘YYYY-MM-DD’ literals. Some database engines use different syntax or do not support every JOIN type. The sample calculations were cross-checked in SQLite, with its date-literal syntax adapted for testing; direct PostgreSQL execution is a separate release check. Real business rules may require additional treatment of returns, refunds, taxes, shipping and payment allocation. PostgreSQL’s official table-expression reference documents the JOIN and ON/WHERE semantics used here.
SQL JOIN Types Explained With Examples
The same relationship produces different results depending on whether unmatched rows are retained. Follow the query and its expected output, then predict which customers will disappear or remain. JOIN without a modifier means INNER JOIN; LEFT OUTER JOIN and LEFT JOIN are interchangeable spellings in PostgreSQL.
INNER JOIN: keep matching customers and orders
An INNER JOIN returns an order only when a related customer exists. With our foreign-key-protected sample, all six orders match customers, so the result contains six rows—including the cancelled order. A JOIN does not automatically filter business status.
| Customer | Order | Status |
|---|---|---|
| Amina | 1001 | completed |
| Brian | 1002 | completed |
| Amina | 1003 | completed |
| Chao | 1004 | completed |
| David | 1005 | cancelled |
| Brian | 1006 | completed |
Why Amina appears twice
Amina placed orders 1001 and 1003. The JOIN returns one row per order; this is correct one-to-many behaviour.
LEFT JOIN: keep customers even without completed orders
For a customer report, begin with customers and LEFT JOIN only completed orders within the five-day window. Keep the right-table status and date conditions in ON so that customers with zero qualifying orders are preserved.
| Customer | Completed orders |
|---|---|
| Amina | 2 |
| Brian | 2 |
| Chao | 1 |
| David | 0 |
| Esther | 0 |
David has zero completed orders because his only order was cancelled. Esther has zero because she never ordered. Both remain visible.
RIGHT JOIN: preserve the right-hand table
A RIGHT JOIN keeps every row from the table written to the right of the JOIN. This query keeps all five customers, including Esther. Most beginner reports are easier to read if you swap table order and use LEFT JOIN instead.
| Customer | Order |
|---|---|
| Amina | 1001 |
| Amina | 1003 |
| Brian | 1002 |
| Brian | 1006 |
| Chao | 1004 |
| David | 1005 |
| Esther | NULL |
There are seven rows because Esther survives without an order, and Amina and Brian each have two orders. The cancelled order 1005 still appears: this query has no order-status filter. Swapping table order and using LEFT JOIN produces equivalent preservation behaviour.
FULL OUTER JOIN: keep unmatched rows from both sides
FULL OUTER JOIN is useful for reconciling two independent lists. Suppose a manager has targets for Migori, Kisumu and Nakuru, while completed sales exist in Migori, Kisumu and Kisii. That creates a match, a sales-only city and a target-only city.
| City | Target (KSh) | Actual (KSh) |
|---|---|---|
| Kisii | — | 250 |
| Kisumu | 4,500 | 4,550 |
| Migori | 3,000 | 3,100 |
| Nakuru | 2,000 | — |
Kisii appears with an actual amount but no target. Nakuru appears with a target but no actual sales entry. These are genuinely unmatched rows on opposite sides; the dash indicates SQL NULL, not zero. Migori and Kisumu have both values.
SQL JOIN types compared
| JOIN | What it preserves | Beginner use |
|---|---|---|
| INNER | Only matching rows | Orders with a matching customer |
| LEFT | Every row on the left | All customers, including non-buyers |
| RIGHT | Every row on the right | Equivalent preservation with tables reversed |
| FULL OUTER | All matched and unmatched rows on either side | Compare two lists with missing members |
| CROSS | Every pair of rows | Generate combinations intentionally |
Two other JOIN patterns you will encounter
CROSS JOIN creates every combination of rows rather than matching keys. Five customers crossed with six orders give 5 × 6 = 30 combinations. Use it only when every pairing is intentional; a JOIN with an overly broad ON condition can also multiply rows unexpectedly:
Self-join: compare two orders
A self-join uses the same table twice under different aliases. The next query finds pairs of orders placed by the same customer, without repeating the reversed pair:
| customer_id | first_order | second_order |
|---|---|---|
| 1 | 1001 | 1003 |
| 2 | 1002 | 1006 |
The self-join shows relationships within orders; it does not calculate revenue and is not needed for the main four-table report. https://www.postgresql.org/docs/current/tutorial-join.html explains this pattern in PostgreSQL’s official tutorial.
Build a Sales Report From Four SQL Tables
We will now create the report progressively. The reporting grain first becomes one order item; later, GROUP BY summarises those detail rows into products or customers.
Decide which records belong in the report
Our training file contains orders dated 1–5 October 2026. That is the complete sample window, but an operational report must explicitly define its own start and end dates rather than silently relying on the contents of a table. For a period that includes 1 October and ends after 5 October, an inclusive-start/exclusive-end filter is:
Keep the reporting period consistent
The completed-sales queries below already include these date bounds. For a different reporting period, update the start and exclusive end dates consistently across every relevant query. A half-open interval also works cleanly with timestamp columns when appropriate: it avoids guessing the final time-of-day value. For the sample dataset, the results remain five completed orders and KSh 7,900. Completed order status does not establish that a customer has paid; actual cash collection, taxes, discounts and refunds require their own records and business rules.
Step 1: Join customers, orders, order items and products
Every required relationship must appear in the query. Use aliases to shorten SQL while keeping column origins clear. The WHERE clause includes only completed orders within the five-day reporting period.
| Order | Customer | Product | Line revenue (KSh) |
|---|---|---|---|
| 1001 | Amina | Notebook | 500 |
| 1001 | Amina | Mouse | 800 |
| 1002 | Brian | Headset | 1,500 |
| 1002 | Brian | Flash Drive | 1,200 |
| 1003 | Amina | Flash Drive | 1,800 |
| 1004 | Chao | Notebook | 250 |
| 1006 | Brian | Mouse | 1,600 |
| 1006 | Brian | Notebook | 250 |
Notice that order 1001 appears twice because it contains two products. This is expected: the query produces one row per order item. The eight lines are not eight separate customer orders.
Step 2: Calculate revenue by product
Multiply quantity by the selling price stored on the order line, exclude cancelled orders, then group by product ID and name.
| Product | Units sold | Revenue (KSh) |
|---|---|---|
| Flash Drive | 5 | 3,000 |
| Mouse | 3 | 2,400 |
| Headset | 1 | 1,500 |
| Notebook | 4 | 1,000 |
Adding the four product totals gives KSh 7,900. The Webcam is missing here because it has no completed sales; an INNER JOIN excludes unmatched products. Use a LEFT JOIN when a report must also display unsold stock items.
Bonus: include unsold products with a LEFT JOIN
For a complete product catalogue report, start from products, LEFT JOIN order items and orders, and count revenue only when the order is completed during the reporting window. This keeps Webcam visible with KSh 0 in completed sales. Notice that a conditional CASE counts qualifying order lines without discarding unmatched products.
| Product | Completed revenue (KSh) |
|---|---|
| Notebook | 1,000 |
| Headset | 1,500 |
| Mouse | 2,400 |
| Flash Drive | 3,000 |
| Webcam | 0 |
Step 3: Produce a customer report, including zero sales
Start from customers and LEFT JOIN only completed orders in the reporting period, followed by their line items. COUNT(DISTINCT o.order_id) counts orders rather than repeated item lines. COALESCE converts a missing SUM to zero for presentation. This measures completed-order line value, not payment receipts or profit.
| Customer | City | Orders | Revenue (KSh) |
|---|---|---|---|
| Brian | Kisumu | 2 | 4,550 |
| Amina | Migori | 2 | 3,100 |
| Chao | Kisii | 1 | 250 |
| David | Nairobi | 0 | 0 |
| Esther | Homa Bay | 0 | 0 |
The report covers every customer, yet only completed order lines contribute to revenue. Brian generated KSh 4,550 and Amina KSh 3,100. A high revenue figure in this tiny demonstration is not evidence of customer profitability; we have no cost or margin data.
Check the totals by order before trusting the grand total
One order can have multiple lines, so first add the lines within each completed order:
| Completed order | Calculation | Order sales value (KSh) |
|---|---|---|
| 1001 | 500 + 800 | 1,300 |
| 1002 | 1,500 + 1,200 | 2,700 |
| 1003 | 1,800 | 1,800 |
| 1004 | 250 | 250 |
| 1006 | 1,600 + 250 | 1,850 |
| Total | 1,300 + 2,700 + 1,800 + 250 + 1,850 | 7,900 |
This hand-check provides a direct way to spot missing or repeated line amounts. It also explains why the cancelled order 1005’s KSh 1,500 must not appear in the total.
Step 4: Reconcile the final report against the details
Check the order headers first. A completed order with zero order lines disappears when an INNER JOIN is applied to order_items; counting the joined rows alone would miss that header. The next query counts qualifying orders directly and flags any completed order without at least one line:
| Completed order headers | Empty completed orders |
|---|---|
| 5 | 0 |
Now check the completed line items. This second query intentionally joins orders to order lines. It should return five distinct joined orders, eight completed lines, and KSh 7,900. Compare its order count with the independent header count above; the two counts agreeing is reassuring, but it does not prove the original transactions were recorded correctly.
| Completed orders | Completed lines | Revenue (KSh) |
|---|---|---|
| 5 | 8 | 7,900 |
Dataset reconciliation result
The order-header check finds 5 completed orders and 0 empty completed orders. The line-level check finds 5 represented orders and 8 lines. Product revenue totals (KSh 7,900), customer revenue totals (KSh 7,900), and line-level revenue (KSh 7,900) agree. These checks detect some common aggregation problems; they do not independently certify that every real-world sale, return, discount or payment was captured in the source system.
Why JOINs Produce Wrong Counts or Inflated Sales
A SQL query can run successfully and still answer the wrong business question. Check the output grain before using COUNT, SUM or averages. These examples illustrate common errors that a simple SQL syntax checker cannot catch. [2]
Mistake 1: COUNT(*) treats order lines as customer orders
The four-table report returns eight rows for only five completed orders. COUNT(*) = 8 counts joined lines. To count distinct completed orders after a line-level join, use COUNT(DISTINCT o.order_id) = 5.
Also be careful with LEFT JOIN: COUNT(*) counts the single preserved row for a customer with no order, while COUNT(o.order_id) returns zero because the joined order ID is NULL. COUNT(DISTINCT o.order_id) is helpful once each order has been repeated across multiple items.
Mistake 2: Repeating an order total on every item line
Suppose we first calculate one order total, then join it back to all the order’s items. An order with two lines appears twice and its full order value is counted twice. This deliberately incorrect query produces KSh 13,750 rather than KSh 7,900.
Why KSh 13,750 is wrong
Order 1001 totals KSh 1,300 but appears on two item rows, contributing KSh 2,600. The same multiplication affects other multi-line orders. The sum is inflated by KSh 5,850.
For this completed-sales report, the correct calculation sums each order item’s quantity × unit_price exactly once. If you need order-level totals, aggregate first and do not then re-sum those totals after expanding them to line level. Do not try to fix this by writing SUM(DISTINCT order_total): two different orders can have the same amount. If two genuine orders are each worth KSh 1,300, their combined value is KSh 2,600, but SUM(DISTINCT order_total) would count that KSh 1,300 only once. The right fix is to aggregate at the intended row grain.
Correct total
The corrected query returns KSh 7,900. It excludes the cancelled order and counts each completed order line once.
Mistake 3: Putting an outer-join filter in WHERE
When you put o.status = ‘completed’ in the WHERE clause after a LEFT JOIN, SQL removes customers with NULL order fields. David and Esther disappear, so a report intended to show every customer no longer does so. PostgreSQL distinguishes the JOIN condition from filtering applied after the join. See the official table-expression rules.
Lost rows in the WHERE version
This query returns only Amina, Brian and Chao. The corrected version below puts the status restriction in ON, preserving David and Esther with zero completed orders.
Remember ON versus WHERE
For this LEFT JOIN, putting a right-table filter in ON affects which orders match; putting it in WHERE removes unmatched customers afterward. For an INNER JOIN, moving this kind of filter between ON and WHERE is equivalent here; with an OUTER JOIN, the change can remove the rows you meant to preserve.
Mistake 4: Joining unrelated ID columns
Check the meaning of every ON comparison. order_items.item_id identifies an individual line, while order_items.product_id identifies the product sold. Joining products.product_id to order_items.item_id would return zero matches in this dataset, even though the SQL is syntactically valid. The correct relationship is products.product_id = order_items.product_id. Naming and foreign-key constraints help, but always verify that the matching columns refer to the same real-world entity.
Quick diagnostic: which JOIN would you choose?
- Only orders with a valid customer: INNER JOIN customers to orders.
- Every customer, including non-buyers: customers LEFT JOIN orders.
- Every product, even with zero completed sales: start from products and LEFT JOIN the sales-side rows.
- A complete comparison of targets and actuals, even if one side is missing: FULL OUTER JOIN two independently prepared lists.
The starting table is as important as the JOIN keyword. Always ask which records must survive when no match exists. USING (customer_id) can abbreviate an equality join when the key has the same name on both sides, but explicit ON is easier for mixed keys and extra filtering. Avoid relying on NATURAL JOIN for critical reports: it automatically joins on every shared column name, so an innocent schema change can alter the matching logic. See the PostgreSQL JOIN reference.
A practical checklist before sharing a report
- State the reporting period, order-status rules, and whether refunds or returns are included.
- Identify whether each row represents a customer, order, order line or product.
- Check every JOIN key and whether the relationship is one-to-one or one-to-many.
- Compare COUNT(*) with COUNT(DISTINCT order_id) when counting orders.
- Check how cancelled orders, NULLs and customers with zero orders are handled.
- Reconcile line-level, customer-level and product-level revenue totals; separately count qualifying order headers and flag those without lines.
- Make the report’s assumptions explicit before a manager makes a decision.
Practice SQL JOINs: Five Exercises and Answers
Run the setup script first, then try each question without copying the solution immediately. Predict the result before executing your SQL.
- List every customer and the number of completed orders during 1–5 October, including zero.
- Find customers who have never placed any order, including cancelled ones.
- Find customers with no completed orders during 1–5 October, even if they have cancelled orders.
- Find products with no completed-order sales during 1–5 October.
- Calculate completed-order revenue during 1–5 October by city, including cities with zero revenue.
Answer 1: completed order counts
Use LEFT JOIN, put the completed status in ON and count the right-table order ID. Expected counts: Amina 2; Brian 2; Chao 1; David 0; Esther 0.
Answer 2: customers who never ordered
Expected result
Esther only. David does not qualify because order 1005 exists, although cancelled.
Answer 3: customers with no completed orders
Expected result
David and Esther. This differs from Exercise 2 because the status condition changes what counts as a match.
Answer 4: products without completed sales
Expected result
Webcam. The HAVING clause counts only order-item matches connected to orders completed within the reporting dates. A product sold only before or after this period would also count as unsold in this period, not necessarily unsold forever.
Answer 5: completed revenue by city
| City | Revenue (KSh) |
|---|---|
| Kisumu | 4,550 |
| Migori | 3,100 |
| Kisii | 250 |
| Homa Bay | 0 |
| Nairobi | 0 |
Practice completion check
Migori, Kisumu and Kisii together account for KSh 7,900. Zero-revenue cities remain in the output. If you get KSh 9,400, you probably included the cancelled order’s KSh 1,500.
SQL JOIN Frequently Asked Questions
What is the difference between INNER JOIN and LEFT JOIN?
INNER JOIN keeps matching row pairs only. LEFT JOIN also preserves unmatched left-table rows and fills their missing right-side columns with NULL. This is why a LEFT JOIN can show customers with zero completed orders.
Does JOIN automatically remove duplicate rows?
No. One customer can match several orders, and one order can match several order lines. Multiple joined rows are expected. Investigate the row grain before using DISTINCT to hide anything.
Can I JOIN more than two SQL tables?
Yes. The detail report joins customers, orders, order_items and products. Each JOIN needs a correct matching key and a clear reason.
Why is my SUM larger after a JOIN?
A one-to-many JOIN can repeat higher-level values on several rows. For example, an order total is repeated if the order is joined back to its line items. Sum at the correct grain, reconcile detail totals, and compare qualifying order-header counts before relying on the report.
What is the difference between ON and WHERE in a LEFT JOIN?
ON decides which right-table rows match; WHERE filters the result after the join. Filtering a right-table value in WHERE often removes otherwise-preserved unmatched left rows.
How do I check whether a JOIN accidentally lost an order?
Count qualifying orders directly from the orders table before joining. Then compare that header count with distinct order IDs in the joined report. If the counts differ, look for orders without items, restrictive filters and missing join matches. Even when totals agree, confirm the business rules and source data separately.
Is FULL OUTER JOIN available in every database?
No. Database engines differ in supported syntax. PostgreSQL supports FULL OUTER JOIN, as used in this lesson. Check the documentation for your chosen engine.
What is the best way to practise SQL JOINs?
Begin with two small tables, predict the output, execute the JOIN, then add a third table and verify row counts. Finally compare line-level totals with GROUP BY reports, as in this lesson.
What to Learn After SQL JOINs
Once you can predict INNER and LEFT JOIN outputs, practise GROUP BY, HAVING, common table expressions (CTEs), CASE, date filters, and basic window functions. A useful next project is a monthly report comparing completed-order revenue across locations.
For a broader analysis project, see NIT’s seven beginner Data Analyst projects. To understand how reporting is used at work, read what a Data Analyst does day to day.
Build Real Data Skills at Newton Institute of Technology
To practise these skills beyond this lesson, explore NIT’s Data Science and Analytics programme. It combines SQL, Excel, Python, data cleaning and reporting; training options include Migori and online study. Confirm current admission details on the programme page.
Learn to retrieve and verify business information.
Build skills for cleaning and analysing datasets.
Turn checked data into useful summaries.
Technical References and Learning Notes
- PostgreSQL Documentation — Joins Between Tables. Official JOIN fundamentals and matched/unmatched examples.
- PostgreSQL Documentation — Table Expressions. JOIN types, JOIN conditions, ON, WHERE and grouping semantics.
- NIT — What Is a Database?. Keys and table relationships for beginners.
- NIT — SQL for Data Analysis. Introductory SQL learning pathway.
Dataset and accuracy: All customer names, transactions and monetary figures are fictional educational examples created for this lesson. The worked results were checked in SQLite with a PostgreSQL-date-literal adaptation, supplemented by adversarial mutation tests, and compared with official PostgreSQL documentation. Direct execution in PostgreSQL is still outstanding. Monetary values are in Kenyan shillings and represent completed-order line revenue only, not gross profit.
Editorial note: Queries use PostgreSQL syntax. Adapt status, payment, refund and tax rules to the actual database and business before using this approach operationally.