BM
Bashar ModallalSOFTWARE · AI · SYSTEMS
SQL and Relational Database Engineering

Beginner · Lesson 3 of 12

Software Architecture

Join Tables Without Counting Twice

A bookshop collects AED 180, but its parcel report claims AED 260. Trace each matching row and repair the SQL without losing an order.

Three wrapped parcels and separate packing slips on a bookshop counter.

A bookshop in Sharjah collects AED 180 from three online orders. The cashier can show you all three payments. Yet the moment you add a parcel number to the afternoon sales report, its total jumps to AED 210. A colleague suggests including orders that have no parcel yet. You try it and the total climbs again, this time to AED 260. No customer has paid a second time. Where did the extra money come from?

Take the packing slips and set them beside the payment records. One customer bought books that ship in two boxes. Both slips point to the same order, and each row of the report now shows the full amount paid for that order. The payment system is fine. The query has changed what one output row represents. We will build the report a piece at a time, predict its row counts, and give the cashier a result that also answers the packing team's question.

اقرأ الدرس بالعربية

Start with a total you can defend

Use a fresh PostgreSQL session for this exercise and keep it open. The temporary tables disappear at the end of the session. Each order records a single completed payment in dirhams. Each parcel records one box prepared against one order. A parcel marked ready is packed but still on the premises. A parcel marked sent has left the shop. Orders can be paid before the team starts packing them.

CREATE TEMP TABLE book_orders (
  order_id integer PRIMARY KEY,
  paid_aed numeric(8,2) NOT NULL
);
CREATE TEMP TABLE parcels (
  parcel_id integer PRIMARY KEY,
  order_id integer NOT NULL REFERENCES book_orders(order_id),
  state text NOT NULL
);
INSERT INTO book_orders VALUES (41,80), (42,50), (43,50);
INSERT INTO parcels VALUES
  (701,41,'sent'), (702,41,'ready'), (703,42,'sent');

Read the two lists separately before joining anything. Order 41 brought in AED 80. Orders 42 and 43 each brought in AED 50. That gives us three payments and AED 180. In the packing room, order 41 has parcel numbers 701 and 702. Order 42 has parcel 703. Order 43 has no parcel number yet. Write down the match counts in order: two, one, zero. These three numbers explain every result we are about to see.

Notice where the identifiers are unique. You could look up parcel 701 and find exactly one packing record. Looking up order number 41 in the parcel table returns two records, both legitimate. A foreign key requires a parcel to name an existing order. It imposes no requirement that an order have a parcel, or that the warehouse ship all the books in one box. Those are decisions about the shop's work, and the table design leaves room for them.

Predict the matching pairs

SELECT o.order_id, o.paid_aed, p.parcel_id, p.state
FROM book_orders AS o
JOIN parcels AS p ON p.order_id = o.order_id
ORDER BY o.order_id, p.parcel_id;

The aliases let us distinguish the order column on the parcel from the identifier on the order itself. For each order, the join condition asks which parcels carry its number. Each matching pair earns a row in the result. Trace the first order with your finger. You get the pair (41, 701), then (41, 702). Move to the second and you get (42, 703). There is no pair to write down for the last order. PostgreSQL's join tutorial illustrates how to read a result assembled from matching records.

This inner join returns three rows. It is tempting to stop checking here because there were also three orders. But scan down the order identifiers and you will see 41 twice and 43 missing. The number of rows happens to agree while the membership has changed. Adding the money column now gives 80 plus 80 plus 50. We repeated one payment worth 80 and omitted another worth 50, leaving an apparent overstatement of 30. That accounts for the first suspicious total without inventing a missing payment.

Is this query useful? Give it to the dispatch clerk who wants one line per parcel with its associated order. The clerk can identify the order on either of the two boxes. The amount is a fact about the entire order on both lines. Calling the column “value of this parcel” would create a different error. The data does not say how much of the order belongs in each box. To report that amount you would need the contents of the parcels and a rule for allocating the payment.

Keep the order waiting to be packed

SELECT o.order_id, o.paid_aed, p.parcel_id
FROM book_orders AS o
LEFT JOIN parcels AS p ON p.order_id = o.order_id
ORDER BY o.order_id, p.parcel_id;

A left outer join keeps order 43 visible. In its output row the parcel number is null because there was no matching packing record. Orders 41 and 42 still produce all their matching pairs. The four rows therefore carry amounts 80, 80, 50 and 50. Their sum is AED 260. The extra 80 can now be traced entirely to the second appearance of order 41. The cashier was right to ask for every order, but preserving every order does not guarantee that it appears exactly once.

Here is a way to estimate the size of either result on paper. For the inner join add the number of matches for each order. For the left join add the same numbers with one adjustment: write a one wherever an order had zero matches. For our example the first sum is two plus one plus zero. The second is two plus one plus one. The extra row in the second result represents an order awaiting packing. It does not represent a fourth parcel. See the PostgreSQL table-expression reference for the rules that preserve unmatched rows.

Build a report with one row per payment

The cashier wants the order number, the amount paid and the number of parcels. They would also like to add up any of the numeric measures across the page. Before writing another join, sketch the expected first line: order 41, AED 80, two parcels. You have already answered the parcel question for that order. The database can do the same work for every order by counting parcels in groups, and then joining those counts to the payments.

CREATE TEMP VIEW order_fulfilment AS
WITH parcel_counts AS (
  SELECT order_id, COUNT(*) AS parcel_count
  FROM parcels
  GROUP BY order_id
)
SELECT o.order_id, o.paid_aed,
       COALESCE(c.parcel_count, 0) AS parcel_count
FROM book_orders AS o
LEFT JOIN parcel_counts AS c ON c.order_id = o.order_id;

SELECT * FROM order_fulfilment ORDER BY order_id;
SELECT COUNT(*) AS orders, SUM(paid_aed) AS collected_aed,
       SUM(parcel_count) AS parcels
FROM order_fulfilment;

Inside the named query, the warehouse records reduce to two rows. Order 41 has a count of two and order 42 has a count of one. Each identifier now occurs at most once on the right side of the join. On the left, each identifier was already unique. That gives an order at most one matching summary, and the left join gives it one result row even when the summary is absent. Both parts matter if you are promising the cashier exactly one line per payment.

Order 43 appears with AED 50 and a parcel count of zero. The expression COALESCE supplies zero when no count arrived from the right. That substitution has a specific justification: we counted a complete list of known parcel records, and there were none for this order. A missing weight or missing price would need a different interpretation. The last query returns three orders, AED 180 and three parcels. Compare those numbers with the two original lists. Both teams can now use the same report and reconcile their totals independently.

What about summing distinct amounts instead? There are only two different payment amounts, 80 and 50. That calculation would give AED 130 and discard a genuine customer's money. Removing duplicate rows from the detailed join is also unreliable: the two parcel numbers on order 41 make its detail rows different. The repair works because you choose an identifier that represents an actual payment and bring parcel facts to that level. Equal numbers printed on two different receipts tell you nothing about the identity of the sale.

To audit a longer report, ask the database to name any order that occupies more than one line. Run the check below against the saved view. An empty result is the expected outcome. This check can catch repeated orders worth zero, which would have no effect on a money total. It cannot tell you whether an order was dropped altogether. For that, read from the original order table and look for an identifier missing from the report. The second query makes that separate check. In this example both checks should return no rows.

SELECT order_id FROM order_fulfilment
GROUP BY order_id HAVING COUNT(*) > 1;

SELECT o.order_id FROM book_orders AS o
WHERE NOT EXISTS (
  SELECT 1 FROM order_fulfilment AS f WHERE f.order_id = o.order_id
);

Count the boxes that have actually left

The warehouse now wants a dispatch column with zero beside any order still waiting for its first shipment. Think about where the status belongs. It describes a parcel. We can require a parcel to be sent before allowing it to match, while keeping every order on our list. Try this query against the original three packing records.

SELECT o.order_id, COUNT(p.parcel_id) AS sent_count
FROM book_orders AS o
LEFT JOIN parcels AS p
  ON p.order_id = o.order_id AND p.state = 'sent'
GROUP BY o.order_id
ORDER BY o.order_id;

You should see counts of one, one and zero. A count of the parcel identifier includes only a real matching parcel. Counting every output row instead would give order 43 a shipment, because its placeholder row exists even though its parcel identifier is null. PostgreSQL explains the difference between counting rows and counting present values in its aggregate function reference.

As a separate experiment, move the status condition out of the join and into a WHERE clause immediately before GROUP BY. The row for order 43 now fails the condition. Its missing parcel state cannot be equal to sent. The report quietly changes from a list of all paid orders with shipment counts to a list restricted to orders with a shipment. Both are reasonable questions. The dispatch supervisor deciding whom to call specifically needs to see the zeroes, so the first version serves that purpose.

Exercise: make the packing team work without taking another payment

Two boxes are prepared just before closing. One is the first parcel for order 43. The other is a third parcel for order 41. Predict the inner join count, the left join count, and the three totals in the cashier's report. Then insert the two rows once and rerun the earlier queries in the same session. A view uses the current table contents each time it is queried.

INSERT INTO parcels VALUES (704,43,'ready'), (705,41,'ready');

Answer. The match counts are now three, one and one. Both detail joins return five rows because every order has at least one box. The cashier's report still has three orders and AED 180, with the parcel total rising from three to five. Sent counts remain one, one and zero because neither new box has left the premises. If revenue changes when you insert these packing slips, locate the first intermediate result where order 41 appears more than once. That is the row set to inspect before trusting the sum.

YOUR TAKE

What did you think?

Choose one reaction for this article.

Was this useful?

A cookie helps limit repeat responses. Your feedback is private.

Share this noteLinkedIn ↗X ↗Email ↗

Keep exploring.

Software Architecture9 min read

Answer Questions with SELECT

Two AED 40 receipts look alike. Should both count? Reconcile a day of shop sales in PostgreSQL, from the first filter to a channel report you can check by hand.

Read article ↗

Software Architecture9 min read

Model a Shop with Tables and Keys

One receipt covers two notebooks and a pen. Build three PostgreSQL tables and see why counting customers, orders, lines and physical pieces gives different answers.

Read article ↗