Turn Business Rules into Constraints
Two approved spreadsheet rows quote different prices for the same notebooks. Normalize a wholesale price list and make PostgreSQL reject the conflicting offer.
Beginner · Lesson 2 of 12
Software Architecture
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.

At closing time, a stationery shop in Sharjah has two paper receipts for AED 40. A colleague has removed the second amount from the day's spreadsheet because it looked like a duplicate. Meanwhile the online till shows an AED 90 order that the customer cancelled. The manager wants to know how much the shop actually sold on 30 November, whether the counter or the website brought in more money, and how many paid receipts carry a coupon code. Which pieces of paper belong in the calculation?
We will answer all three questions from the same small ledger in PostgreSQL. Keep a pencil handy. The point of seven input rows is that you can challenge the database's answer with a sum you understand. By the end you should be able to tell the manager exactly why two identical amounts belong in revenue, why a zero belongs in the receipt count, and what a blank total on a quiet channel means.
For this report, one row represents one checkout receipt. Its identifier identifies that sale even when another customer spends exactly the same amount. The channel is where the order was taken. The amount on a paid receipt is the final amount collected in dirhams after discounts. A cancelled order keeps its quoted amount for customer service. A paid receipt may legitimately have a zero balance when a gift covers the entire purchase. The business asks us to include that receipt among completed checkouts.
Open a PostgreSQL session and run the setup once. Keep the same session open for the whole lesson because the table and the view we will create are temporary. The ledger stores the shop's local business date explicitly. This lets us match a calendar day directly without assuming that a payment system and a shop always close their books in the same time zone.
CREATE TEMP TABLE sq02_sales (
receipt_id integer PRIMARY KEY,
sale_day date NOT NULL,
channel text NOT NULL,
status text NOT NULL,
amount_aed numeric(8,2) NOT NULL,
coupon text
);
INSERT INTO sq02_sales VALUES
(101, '2026-11-30', 'shop', 'paid', 40, NULL),
(102, '2026-11-30', 'shop', 'paid', 40, NULL),
(103, '2026-11-30', 'web', 'paid', 20, 'SAVE'),
(104, '2026-11-30', 'web', 'paid', 60, NULL),
(105, '2026-11-30', 'web', 'cancelled', 90, NULL),
(106, '2026-11-30', 'shop', 'paid', 0, 'GIFT'),
(107, '2026-12-01', 'shop', 'paid', 15, NULL);
Before writing a query, cover up the amounts and circle the identifiers you would hand to someone checking the report. You should have 101, 102, 103, 104 and 106. Receipt 105 has the right date and the wrong status. Receipt 107 has the right status and the wrong date. Finding the eligible receipts first gives you a way to investigate a surprising total later. A single number at the bottom of a spreadsheet loses that trail.
SELECT receipt_id, channel, amount_aed, coupon
FROM sq02_sales
WHERE sale_day = DATE '2026-11-30'
AND status = 'paid'
ORDER BY amount_aed DESC, receipt_id ASC;
Read the query aloud from the table name. Starting with the ledger, keep a row when both conditions hold, return the four named fields, then put the largest payments first. Naming the columns tells a colleague what they need to inspect and in which units. Returning the identifier also gives customer service a way to find the original receipt. The sort is for presentation. It changes neither the values nor the number of receipts. PostgreSQL describes the role of each clause in its SELECT reference.
The result starts with receipt 104 at AED 60. Next come 101 and 102 at AED 40 each, followed by 103 at AED 20 and 106 at zero. The second sort key settles the tie between the two forties using their unique receipt numbers. Without this instruction either of those receipts could precede the other. A colleague printing the top two would then get a perfectly plausible list whose second receipt could change. For a report that needs one reproducible order, specify how to break every meaningful tie. See PostgreSQL's guide to sorting rows.
Give those eligible receipts a name for the rest of the exercise. A view saves a query definition. Reading it evaluates that definition against the underlying table, so a new qualifying sale will show up when we run the exercise at the end. We deliberately leave the presentation order out of the view. Each question can now choose its own order without changing which receipts are eligible.
CREATE TEMP VIEW sq02_paid_day AS
SELECT receipt_id, channel, amount_aed, coupon
FROM sq02_sales
WHERE sale_day = DATE '2026-11-30'
AND status = 'paid';
The manager's coupon question sounds like a request to count customers. Look at the available information first. A receipt has an optional code and no customer identifier. We can count paid receipts with a recorded code. We cannot count distinct people, or infer the cashier's reason for leaving the code field blank. That distinction matters when someone labels the result “customers who paid full price.” A missing code alone gives us no evidence about other discounts.
SELECT receipt_id, coupon
FROM sq02_paid_day
WHERE coupon IS NULL
ORDER BY receipt_id;
SELECT COUNT(*) AS receipts, COUNT(coupon) AS with_code,
COUNT(DISTINCT amount_aed) AS different_amounts,
SUM(amount_aed) AS revenue_aed
FROM sq02_paid_day;
The first query returns receipts 101, 102 and 104. SQL uses a special marker, NULL, for an absent value. An ordinary equality test against that marker produces an unknown result. A row passes a filter only when the condition is true, so writing coupon = NULL would silently return an empty list here. Use IS NULL to ask the question directly. An empty string, if your intake system stores one, is a present text value and needs its own business rule. PostgreSQL explains these cases in comparison functions and operators.
The second query gives five receipts, two with a code, four different amounts and AED 160 in revenue. Follow the four calculations across the same pile of receipts. Counting rows includes the gift purchase. Counting the coupon field visits the two present codes, SAVE and GIFT. Counting distinct amounts sees 0, 20, 40 and 60 once each. Summing the amount visits all five receipts, including both forties. These calculations give different numbers because they answer different questions about the same events.
Suppose you encounter SUM(DISTINCT amount_aed) in the original spreadsheet replacement. It would return AED 120. You can explain the missing AED 40 by pointing to receipts 101 and 102 side by side. Equal prices tell us nothing about whether the sales are the same. If an import really does replay a receipt, investigate its identifier and the import history. Removing repeated prices would also erase genuine sales from the report. In this exercise the primary key already keeps the table from accepting a second row for the same receipt number.
SELECT channel, COUNT(*) AS receipts, COUNT(coupon) AS with_code,
SUM(amount_aed) AS revenue_aed
FROM sq02_paid_day
GROUP BY channel
ORDER BY revenue_aed DESC, channel ASC;
Imagine dividing the five pieces of paper into two piles. The shop pile has three receipts with amounts 40, 40 and 0. The web pile has two receipts worth 20 and 60. Each pile contains one recorded coupon. The result has two rows because we asked for one row per channel. The two channels tie at AED 80. The counter completed more checkouts, and the website collected more per checkout on average. This is a case where reporting just the name of the first channel would give the manager the wrong impression of the result.
A quick reconciliation checks two separate things. The group counts must add up to the number of eligible receipts, and the group totals must add up to the money collected. Three plus two gives five, and eighty plus eighty gives one hundred and sixty. Checking only the money would miss an accidentally omitted zero-value receipt. Checking only the count would miss a report that adds each distinct amount once. Keep both measures beside each other while you develop a report.
Now the manager asks which channels took at least AED 75 that day. Decide whether the threshold belongs to a receipt or a pile before choosing the clause. Both channels qualify on their daily total, although the largest individual receipt was only AED 60. Filtering individual amounts to 75 or more would discard all five rows before the database had a chance to add them.
SELECT channel, SUM(amount_aed) AS revenue_aed
FROM sq02_paid_day
GROUP BY channel
HAVING SUM(amount_aed) >= 75
ORDER BY revenue_aed DESC, channel ASC;
Try raising the threshold from 75 to 81 and predict the result before running it. Neither group reaches 81, so you should get a column header with no data rows. That observation gives the reporting interface an appropriate message, “No channel reached the threshold.” It would be inaccurate to tell the manager there were no sales that day. Five sales went into the calculation even though neither group met the condition for display.
A phone-order pilot starts tomorrow. What should today's dashboard show for the phone channel? A grouped query over the paid receipts has no phone group because there is no matching receipt. For a single summary card you can instead ask for an aggregate across all matching rows, without grouping by channel. Run this query before adding any new sales.
SELECT COUNT(*) AS receipts, SUM(amount_aed) AS raw_total,
COALESCE(SUM(amount_aed), 0) AS display_total
FROM sq02_paid_day
WHERE channel = 'phone';
You get one summary row. Its receipt count is zero, its raw total is null, and its display total is zero. Compare that with filtering the same query down to receipt 106 instead of the phone channel. For the gift purchase the count is one, the raw total is zero and the display total is also zero. A card that shows only “AED 0” hides a useful difference between inactivity and a completed checkout. Displaying the count alongside the amount makes that difference visible. Use the zero substitution when it fits the display contract, and retain the raw measure when its absence carries information. PostgreSQL documents how aggregate functions handle empty inputs.
A web payment reaches the ledger before the tills close. Before running the insert, write down which channel will lead, the total number of paid receipts, and how many receipts will have a recorded coupon. Predict the count of distinct amounts as well. Then add this receipt once and rerun the view-based queries. The original date and status conditions still apply.
INSERT INTO sq02_sales VALUES
(108, '2026-11-30', 'web', 'paid', 40, NULL);
Answer. Web leads with AED 120 from three receipts. Shop stays at AED 80 from three. Across both channels you should see six paid receipts, AED 200 collected, two receipts with a recorded coupon and four distinct amounts. The new customer paid an amount already present and supplied no code, so neither of the last two measures increases. For a final check, raise the channel threshold to AED 100. Your result should contain exactly one row, for the website. If your report shows AED 160 for the day after the insert, find receipt 108 in the detail output and follow its AED 40 through the web pile into the total.
YOUR TAKE
Choose one reaction for this article.
A cookie helps limit repeat responses. Your feedback is private.