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

A school orders twelve blue notebooks from a stationery wholesaler. The buyer was quoted AED 10 per notebook. The new order screen offers AED 9.50 for exactly the same quantity. Both prices came from the approved spreadsheet. Look closely and you find two rows for notebook N7 on the school list, both starting at ten units. The importer gave them different row numbers, so its duplicate check passed. Which price should the cashier charge?
The sales manager confirms that AED 10 is correct. That resolves today's dispute but leaves tomorrow's import wide open. Our job is to express the agreement in PostgreSQL so a clerk, an import job and a future integration all get the same answer. We'll build a small price list, quote the school order, then deliberately send it bad data. The useful evidence is what remains in the database after each attempted write.
Ask the sales manager to complete this sentence: “There can be only one current unit price for this combination of …” In this shop the answer is the price list, the product and the minimum quantity. The school list may have its own price for N7 even when a shop-counter list already has one. A new quantity break on the school list is also legitimate. Changing only the amount on an existing break is a revision to that offer. It cannot create a second current offer alongside the first.
The manager also specifies how to read the breaks. Take the largest minimum that the order quantity reaches, and apply its unit price to every notebook in the order. This is different from a calculation that charges a higher rate for the first nine notebooks and a lower rate only on later units. Write down that decision before working on the query. A database can store impeccably consistent tiers for a pricing policy the cashier never intended.
All prices here are current, in UAE dirhams, and positive. We will store them as whole fils, with one hundred fils to the dirham. A price of 875 therefore means AED 8.75. The list stores thresholds in whole units. Delivery charges, taxes, dated offers and free promotional items are outside this particular price agreement. Those details matter because a rule as simple as “unit price must be positive” would reject a genuine free promotion in a shop that permits one.
On the old sheet the words “Blue notebook” appear beside every quantity break and again on each list. If the product is renamed, a clerk must change all those cells. Miss one and a printed quote may show two names for the same stock code. The list title has the same problem. You cannot reliably correct the discrepancy by choosing whichever spelling appears most often. The extra copies are what made a vote seem necessary in the first place.
Give the product a record of its own, identified by its stable stock code. Give the price list a record of its own as well. Then keep the facts that depend on the whole combination in a third table. A tier says what one unit costs on a particular list for a particular product starting at a particular quantity. You can now rename the notebook once, and you can create a new list before anyone has entered prices for it. This separation of facts according to what determines them is the normalization step.
Open a fresh PostgreSQL session and keep it open throughout the exercise. The temporary tables belong to the session. Run the definitions and seed rows once, with autocommit enabled for setup.
CREATE TEMP TABLE product (
sku text PRIMARY KEY,
display_name text NOT NULL
);
CREATE TEMP TABLE price_list (
list_code text PRIMARY KEY,
label text NOT NULL
);
CREATE TEMP TABLE price_tier (
list_code text REFERENCES price_list(list_code),
sku text REFERENCES product(sku),
min_qty integer CONSTRAINT positive_break CHECK (min_qty > 0),
unit_fils integer NOT NULL
CONSTRAINT positive_price CHECK (unit_fils > 0),
CONSTRAINT one_price_per_break PRIMARY KEY (list_code, sku, min_qty)
);
Read the last line of the tier definition as the manager's agreement. The three columns together form the primary key. Each must have a value, and the combination must be unique. The two references require the list and product to exist. A check on the threshold rules out zero and negative quantities. The price needs both a value and a lower bound. A check expression involving a missing value can evaluate to unknown and still pass a PostgreSQL check. Here an explicit requirement for a non-null price closes that gap. See the PostgreSQL constraint guide.
INSERT INTO product VALUES ('N7','Blue notebook'), ('P2','Black pen');
INSERT INTO price_list VALUES ('SCHOOL','School orders'), ('SHOP','Counter sales');
INSERT INTO price_tier VALUES
('SCHOOL','N7',1,1200), ('SCHOOL','N7',10,1000),
('SHOP','N7',1,1250), ('SCHOOL','P2',1,300);
The four seed offers include two prices for N7 on the school list. They are legal because the thresholds differ. They also include a counter price for one N7 and a school price for one P2. Both are useful test cases. If the query forgets its list or product filter, it may read an offer belonging to a different buyer or a different item. A unique key protects the meaning of a stored offer. The lookup still has to ask for the correct one.
SELECT min_qty, unit_fils, 12 * unit_fils AS total_fils
FROM price_tier
WHERE list_code = 'SCHOOL' AND sku = 'N7' AND min_qty <= 12
ORDER BY min_qty DESC
LIMIT 1;
Walk through the query without the final limit. Only the school notebook offers starting at one and ten qualify. Sorting the thresholds from high to low puts ten first. The result is the threshold 10, unit price 1000 and total 12000 fils, or AED 120. Change both occurrences of twelve to nine and only the first tier qualifies. Nine notebooks then cost AED 108. At exactly ten, the lower unit price applies and the total becomes AED 100. That drop across the boundary follows the shop's all-units discount rule; it is worth showing to the person approving the tariff.
The disputed spreadsheet row tries to introduce a price of 950 fils for the existing ten-unit break. It has a valid product, a valid list, a positive quantity and a positive price. Only the business identity is wrong. This is a good rejection test because it isolates one rule. In a PostgreSQL client that lets you run commands interactively, execute the next example statement by statement. After the expected error, continue at the rollback command.
BEGIN;
SAVEPOINT before_probe;
INSERT INTO price_tier VALUES ('SCHOOL','N7',10,950);
-- After the expected error, issue the following separately:
ROLLBACK TO SAVEPOINT before_probe;
SELECT COUNT(*) FROM price_tier;
COMMIT;
The insert should report a uniqueness violation naming the primary key, with SQLSTATE 23505. Rolling back to the savepoint clears the failed attempt inside the transaction. The count returns four. Repeating the quote returns the original AED 120. That last check matters: a loader that silently updated the existing row would also leave four rows, but the quote would now be AED 114. Testing both row count and price distinguishes rejection from an accidental overwrite. PostgreSQL documents the transaction boundary in its SAVEPOINT reference.
If a price revision really was approved, the write should identify the existing tier and change its price intentionally. In a system where two clerks can revise prices, a revision can also check the previous price or a version before applying the update. An automatic “replace on duplicate” policy makes the last import the winner even when a spreadsheet is out of date. Unique storage and a well-defined revision policy solve two separate problems.
-- Run each separately with autocommit enabled.
INSERT INTO price_tier VALUES ('SCHOOL','N9',5,900);
INSERT INTO price_tier VALUES ('SCHOOL','N7',0,900);
INSERT INTO price_tier VALUES ('SCHOOL','N7',5,NULL);
INSERT INTO price_tier VALUES ('SCHOOL','N7',5,-1);
The first attempt names N9, a stock code absent from the catalog. Expect a foreign-key violation, 23503. The second has a known product and list but a threshold of zero. Expect a check violation, 23514, on positive_break. The third omits the price and should report a not-null violation, 23502. The last supplies a price below zero and fails positive_price with 23514. Each attempted write leaves the four approved offers available. A useful importer records the rejected source row and the failing rule so the clerk can correct the right cell. The PostgreSQL error-code appendix lists the stable codes used here.
Why bother with database enforcement if the import preview already flags duplicates? Consider two staff members previewing a new twenty-five-unit break before either saves. Both previews can truthfully report that the tier is available. Once one insert commits, the other cannot commit a second row with that same key. The second writer can fetch the saved amount and ask whether the user meant to revise it. The preview helps people enter good data. The database also arbitrates between writers who could not see one another's pending changes.
There are limits to what this design proves. If someone loads only a ten-unit tier for a new product, every stored row can be valid and a request for three units can still find no price. Returning zero money in that situation would give away goods because of a missing offer. Return an explicit unavailable-quote outcome instead. If the shop requires a one-unit starting tier for every sellable product on every active list, check coverage when activating the list. A positive-quantity check on an individual row cannot prove that another required row exists.
Keep the conflicting source rows in a staging table while the manager resolves them. Suppose the imported rows expose the same four columns as the tier table, plus their original spreadsheet row numbers. Group them by list, stock code and quantity break. A count greater than one identifies a repeated business record. Counting distinct prices within that group tells you whether all copies agree on the amount. For the disputed ten-unit break you expect two rows and two prices. Neither the lowest amount nor the latest row number proves what the manager approved. Record that decision against the source rows and load one resolved tier. Run the twelve-notebook quote against the new list before pointing the till at it.
A school wants twenty-four notebooks, then considers buying twenty-five. The manager approves a new break at twenty-five for 875 fils per unit. Predict both quotes, insert the approved break once, and rerun the lookup with each quantity substituted in both places. Finally try to add a second row with exactly the same list, product and threshold at 850 fils. Check the stored price as well as the row count.
INSERT INTO price_tier (list_code,sku,min_qty,unit_fils)
VALUES ('SCHOOL','N7',25,875);
Answer. Twenty-four notebooks use the ten-unit tier and cost AED 240. Twenty-five use the new price and cost 21875 fils, or AED 218.75. The duplicate raises 23505. You should still have five tiers, including exactly one school N7 record at twenty-five, priced at 875 fils. You can hand the manager both quotes and point to the specific row that justifies each one.
YOUR TAKE
Choose one reaction for this article.
A cookie helps limit repeat responses. Your feedback is private.