Null-safe order totals with discounts and shipping
The checkout table leaves discount and shipping_fee as NULL when they do not apply, which silently breaks arithmetic totals.
From checkout_lines, return line_id, gross_amount, discount_applied (0 when missing), shipping_charged (0 when missing) and net_payable = gross − discount + shipping, treating missing values as 0. Also return coupon_label, which should read No coupon when coupon_code is NULL.
Sample data
Table: checkout_lines
12 row(s) · showing first 8
| line_idINT | gross_amountNUMERIC(10,2) | discountNUMERIC(10,2) | shipping_feeNUMERIC(10,2) | coupon_codeTEXT |
|---|---|---|---|---|
| 1 | 1200.00 | 100.00 | 40.00 | SAVE100 |
| 2 | 899.00 | NULL | 40.00 | NULL |
| 3 | 2450.50 | 250.00 | NULL | FLAT250 |
| 4 | 349.00 | NULL | NULL | NULL |
| 5 | 5600.00 | 560.00 | 0.00 | TEN |
| 6 | 749.99 | 50.00 | NULL | FIFTY |
| 7 | 1899.00 | NULL | 60.00 | NULL |
| 8 | 3200.00 | 320.00 | 40.00 | TEN |
checkout_lines
- line_idINT
- gross_amountNUMERIC(10,2)
- discountNUMERIC(10,2)
- shipping_feeNUMERIC(10,2)
- coupon_codeTEXT
- Step 1: Remember the core rule: any arithmetic involving `NULL` returns `NULL`, so `gross_amount - discount` would wipe out valid totals.
- Step 2: Wrap each optional numeric column in `COALESCE(col, 0)` to substitute a neutral value.
- Step 3: Build `net_payable` from those coalesced expressions so every row produces a real number.
- Step 4: `COALESCE` works on text too — `COALESCE(coupon_code, 'No coupon')` gives the reporting label.
- Step 5: Project the requested columns with clear aliases.
SELECT line_id,
gross_amount,
COALESCE(discount, 0) AS discount_applied,
COALESCE(shipping_fee, 0) AS shipping_charged,
gross_amount - COALESCE(discount, 0) + COALESCE(shipping_fee, 0) AS net_payable,
COALESCE(coupon_code, 'No coupon') AS coupon_label
FROM checkout_lines;Approach 2 — CASE instead of COALESCE
Functionally identical; useful when you need more than a simple substitution.
SELECT line_id,
gross_amount,
CASE WHEN discount IS NULL THEN 0 ELSE discount END AS discount_applied,
CASE WHEN shipping_fee IS NULL THEN 0 ELSE shipping_fee END AS shipping_charged,
gross_amount
- CASE WHEN discount IS NULL THEN 0 ELSE discount END
+ CASE WHEN shipping_fee IS NULL THEN 0 ELSE shipping_fee END AS net_payable,
CASE WHEN coupon_code IS NULL THEN 'No coupon' ELSE coupon_code END AS coupon_label
FROM checkout_lines;Learn the concept first
Stuck on NULL / NOT NULL Handling? These free SQL lessons teach it step by step.
More NULL / NOT NULL Handling questions
Practising alone only goes so far — our live cohorts pair SQL depth with dashboards, agentic analytics projects and mock interviews.
Explore the program