smartyfy.mrindigi.com

Databases & SQL Master Course — 028. Counting Entities After Joins

Lesson 028 Counting Entities After Joins

Combining four orders with their lines can produce six result rows. The result represents matches plus a retained order without a line. This preview introduces enough join syntax to inspect that changed grain before counting. The next module develops joins further.

Prerequisites and objectives

Complete Lesson 027. You should know primary keys, COUNT, DISTINCT, grouping, and NULL. No earlier knowledge of JOIN syntax is assumed.

Outcome: Detect inflated counts and choose a counting strategy appropriate to joined grain.

Trace matched pairs, compare INNER and LEFT JOIN, and select the key that counts the requested entity.

SQLite lab setup

The examples were executed with Python’s standard-library sqlite3 module, SQLite 3.53.1. Use a fresh SQLite database and run this complete setup once. These examples use SQLite’s arithmetic and aggregate behavior; check the corresponding rules before adapting them to another SQL dialect.

CREATE TABLE orders (
 order_id INTEGER PRIMARY KEY,
 customer_id INTEGER
);
CREATE TABLE order_lines (
 line_id INTEGER PRIMARY KEY,
 order_id INTEGER NOT NULL,
 units INTEGER NOT NULL
);
INSERT INTO orders VALUES (101,7),(102,8),(103,7),(104,NULL);
INSERT INTO order_lines VALUES
 (201,101,2),(202,101,1),(203,102,0),
 (204,104,1),(205,104,1);

Step 1: Inspect both grains

The fictional craft shop’s orders table contains one row per order. order_id uniquely identifies an order; customer_id identifies a known customer and is NULL for a guest order. The order_lines table contains one row per line, with units measured in individual items. Its order_id points to the owning order by the fixture’s data contract. This small setup omits a foreign-key constraint so the lesson can focus on counting. Every supplied line has a parent.

Step 2: Read an explicit match condition

FROM orders AS o gives orders the short table alias o. The qualified name o.order_id distinguishes the parent column from the child’s order_id. INNER JOIN order_lines AS l introduces the second table. ON o.order_id = l.order_id is the matching rule: retain a combined row for each pair whose order identifiers are equal. It is not a request to merge all matching lines into one row.

SELECT o.order_id, l.line_id, l.units
FROM orders AS o
INNER JOIN order_lines AS l ON o.order_id = l.order_id
ORDER BY o.order_id, l.line_id;

Expected pairs are 101/201, 101/202, 102/203, 104/204, and 104/205, with quantities 2, 1, 0, 1, and 1. Order 101 appears twice because it has two lines. Order 103 is absent because INNER JOIN retains only matches. The query’s five rows therefore do not mean five orders. Two lines with the same quantity still represent two different line identities.

Step 3: Understand preserved parents

Replacing INNER JOIN with LEFT JOIN keeps each order even if it has no matching line. An unmatched order receives one result row with NULL right-hand columns. Order 103 therefore appears once with a NULL line_id and NULL units. This preserves the set of order identities, but does not preserve one output row per order: orders with multiple matching lines still multiply. Preservation of entities and preservation of row grain are different promises.

Order101 matches distinct lines201 and202;102 matches203;103 has no matching line;104 matches distinct lines204 and205, both with units1. Six LEFT JOIN pairs include103→NULL as a highlighted preserved unmatched row. Badges count six result rows, five real lines and four distinct orders.
LEFT JOIN preserves order 103 with NULL child columns. Six result rows therefore represent five real lines and four distinct orders; matching multiple lines repeats a parent in the result. Open full-size diagram

Step 4: Match the counter to the entity

COUNT(*) measures result rows. COUNT(l.line_id) measures matched lines because real line keys are non-NULL and the unmatched placeholder has no key. COUNT(DISTINCT o.order_id) measures represented orders, removing repeated order identifiers. Choose the expression from the question, then predict its value from a few row pairs. DISTINCT can repair a count’s grain; it does not automatically repair sums of other repeated columns.

Exercise 1

Count rows, matched lines, and represented orders after the inner join. Predict all three numbers before running the query. Explain which order is missing and why the output cannot answer how many orders exist in the original table.

Worked answer and explanation
SELECT COUNT(*) AS joined_rows,
       COUNT(l.line_id) AS matched_lines,
       COUNT(DISTINCT o.order_id) AS represented_orders
FROM orders AS o
INNER JOIN order_lines AS l ON o.order_id = l.order_id;

The output is 5, 5, and 3. Every inner-join row has a real line, but only orders 101, 102, and 104 are represented. Order 103 has no line. For a count of all orders, count the parent table directly or intentionally preserve it with a left join; deduplicating an inner result cannot restore an absent parent.

Exercise 2

Repeat the three counters using a left join. Identify the additional output row and decide whether it should increase the line count. Keep the original matching condition unchanged so only the preservation rule changes.

Worked answer and explanation
SELECT COUNT(*) AS joined_rows,
       COUNT(l.line_id) AS matched_lines,
       COUNT(DISTINCT o.order_id) AS represented_orders
FROM orders AS o
LEFT JOIN order_lines AS l ON o.order_id = l.order_id;

The output is 6, 5, and 4. The extra row preserves order 103, with NULL line columns. COUNT(*) includes that row; COUNT(l.line_id) does not. Distinct order keys now cover all four parents. Notice that simply counting the non-NULL parent key without DISTINCT would still return six because repeated parents remain non-NULL.

Exercise 3

Produce one row per order with its joined-row count and actual line count. Use the contrast to show why COUNT(*) is misleading for a line-count report that must include orders with zero lines.

Worked answer and explanation
SELECT o.order_id, COUNT(*) AS joined_rows,
       COUNT(l.line_id) AS lines
FROM orders AS o
LEFT JOIN order_lines AS l ON o.order_id = l.order_id
GROUP BY o.order_id ORDER BY o.order_id;

Results are 101: 2 and 2; 102: 1 and 1; 103: 1 and 0; 104: 2 and 2. The zero-unit line 203 is still one line; an unmatched placeholder is not. Count child identities to distinguish line existence from item quantity.

Exercise 4

Group the left-joined report by customer_id, counting orders and lines separately. Keep the NULL customer group visible. Explain what that group measures and why its row does not establish the number of distinct anonymous people.

Worked answer and explanation
SELECT o.customer_id,
       COUNT(DISTINCT o.order_id) AS orders,
       COUNT(l.line_id) AS lines
FROM orders AS o
LEFT JOIN order_lines AS l ON o.order_id = l.order_id
GROUP BY o.customer_id ORDER BY o.customer_id;

SQLite orders the NULL group first here: NULL has one order and two lines; customer 7 has two orders and two lines; customer 8 has one order and one line. Customer 7’s empty order survives. The NULL bucket means unknown customer identity, not one identified person. Two guest orders could belong to one person or several; these columns cannot decide.

Pitfalls and practical review

Always inspect keys before applying DISTINCT. Removing repeated quantities would discard legitimate lines 204 and 205. A second child table can multiply matches again, so distinct order counts do not certify unrelated totals. Avoid adding a right-table filter in WHERE without checking unmatched parents: a condition requiring a real child value can remove them. For this lesson, retain the simple join condition and validate the small fixture before expanding its scope.

Question 1

Why does order 101 appear twice in the inner join?

  1. The primary key stopped working
  2. Two different lines match its order key
  3. Every order must appear at least twice
  4. DISTINCT is applied after every join
Answer and explanation

B. The result represents matching pairs, and each line supplies a separate pair. The parent remains unique in its own table. Sorting merely arranges the result; it does not determine its entity grain.

Question 2

Which expression counts real lines after this left join?

  1. COUNT(*)
  2. COUNT(o.order_id)
  3. COUNT(l.line_id)
  4. COUNT(DISTINCT l.units)
Answer and explanation

C. Actual child keys are non-NULL, while an unmatched placeholder has a NULL child key. The first two count placeholder rows, and distinct quantities count different quantity values rather than line identities.

Question 3

What happens to order 103 in the inner join?

  1. It receives a zero line identifier
  2. It appears twice
  3. It remains with a NULL line
  4. It is absent because no line matches
Answer and explanation

D. An inner join keeps matching pairs only. A left join is the operation in this preview that deliberately retains an unmatched parent with NULL right-hand columns.

Question 4

Does LEFT JOIN guarantee one result row per order?

  1. No, multiple matching lines still repeat the order
  2. Yes, every left table is automatically grouped
  3. Yes, unless ORDER BY is present
  4. Only when COUNT is omitted
Answer and explanation

A. The operation preserves parent identities, not necessarily parent row grain. Grouping by the order key can produce an order-level report, but the join alone does not perform that aggregation.

Question 5

Why not count distinct quantities to remove apparent duplicates?

  1. DISTINCT only accepts text
  2. Quantities are always NULL
  3. Different lines can have equal quantities
  4. Quantity is an order key
Answer and explanation

C. Lines 204 and 205 each contain one item and remain distinct business records. Deduplicating a measure confuses repeated values with repeated entities. Use the identifier appropriate to the question.

Summary

After a join, trace matching pairs, decide whether unmatched parents belong, and count keys at the intended grain. Inspecting parent and child identifiers explains inflated numbers before applying DISTINCT.

Official references