Per-Customer Order Aggregates with Null Amounts
Medium · Data Manipulation (SQL/Python) · Data Scientist · Technical Screen
Problem Statement
An e-commerce ledger stores customer purchase headers in an orders table where the monetary amount may be NULL while an order is still awaiting final settlement or invoice reconciliation. Write a SQL query that summarizes order activity for every customer_id appearing in orders, respecting standard SQL NULL aggregation semantics.
For each distinct customer_id, return one row with these seven columns:
customer_id: the customer's identifier.order_count: total number of order rows placed by this customer, including rows whoseamountisNULL.amount_count: number of order rows for this customer that have a non-NULLamount.total_amount: sum of non-NULLamountvalues for this customer, orNULLif none of the customer's orders have a non-NULLamount.avg_amount: arithmetic mean of non-NULLamountvalues for this customer, rounded to4decimal places, orNULLif no non-NULLamountexists.first_order_date: earliestorder_dateacross all orders placed by this customer (including orders whereamountisNULL).last_order_date: latestorder_dateacross all orders placed by this customer (including orders whereamountisNULL).
Return the output rows in any order.
Input Schema
orders
| Column | Type | Description |
|---|---|---|
order_id |
INTEGER |
Unique order identifier |
customer_id |
INTEGER |
Identifier of the customer who placed the order |
order_date |
DATE |
Calendar date the order was recorded ('YYYY-MM-DD') |
amount |
DECIMAL(10,2) |
Billed order total, or NULL when unpriced/pending |
Examples
Example 1
Input:
orders
order_id |
customer_id |
order_date |
amount |
|---|---|---|---|
| 501 | 10 | 2025-03-04 | 45.00 |
| 502 | 10 | 2025-03-12 | NULL |
| 503 | 10 | 2025-03-19 | 75.00 |
| 504 | 20 | 2025-03-08 | 64.50 |
| 505 | 30 | 2025-03-15 | NULL |
Output:
customer_id |
order_count |
amount_count |
total_amount |
avg_amount |
first_order_date |
last_order_date |
|---|---|---|---|---|---|---|
| 10 | 3 | 2 | 120.0 | 60.0 | 2025-03-04 | 2025-03-19 |
| 20 | 1 | 1 | 64.5 | 64.5 | 2025-03-08 | 2025-03-08 |
| 30 | 1 | 0 | NULL | NULL | 2025-03-15 | 2025-03-15 |
Explanation:
- Customer
10has3orders in total,2of which carry priced amounts (45.00and75.00). Their sum is120.0and their average divides by the2priced rows (120.0 / 2 = 60.0), not all3orders. - Customer
20has a single priced order of64.50on2025-03-08. - Customer
30has1order whoseamountisNULL, soamount_count = 0and bothtotal_amountandavg_amountremainNULL, whilefirst_order_dateandlast_order_dateare both'2025-03-15'.
Example 2
Input:
orders
order_id |
customer_id |
order_date |
amount |
|---|---|---|---|
| 601 | 40 | 2025-04-02 | NULL |
| 602 | 40 | 2025-04-10 | 0.00 |
| 603 | 40 | 2025-04-14 | 50.00 |
| 604 | 40 | 2025-04-21 | 50.00 |
Output:
customer_id |
order_count |
amount_count |
total_amount |
avg_amount |
first_order_date |
last_order_date |
|---|---|---|---|---|---|---|
| 40 | 4 | 3 | 100.0 | 33.3333 | 2025-04-02 | 2025-04-21 |
Explanation:
Order 601 has amount = NULL, yet its date ('2025-04-02') still sets first_order_date. Order 602 has amount = 0.00 — a known zero rather than NULL — so amount_count is 3, total_amount is 100.0, and avg_amount is 100.0 / 3 rounded to 33.3333.
Constraints
order_idis unique acrossorders;order_dateis neverNULL.amountmay be positive,0, negative (for refunds or credits), orNULL.- If
ordersis empty, return zero rows. - Output row order does not matter.
Step-by-step walkthrough
Restate the per-customer summary task
Over
orders(order_id, customer_id, order_date, amount), we need to return one summary row percustomer_idpresent inorders(in any row order) with seven columns:Column SQL expression Meaning when some or all amounts are NULL customer_id customer_id The customer who placed the order(s) order_count COUNT(*) Total order rows for this customer (includes NULL amounts) amount_count COUNT(amount) Orders whose amount is NOT NULL total_amount SUM(amount) Sum of non-NULL amounts; NULL if none exist avg_amount ROUND(AVG(amount), 4) Mean of non-NULL amounts to 4 decimals; NULL if none exist first_order_date MIN(order_date) Earliest order_date across all orders for this customer last_order_date MAX(order_date) Latest order_date across all orders for this customerThe core principle is how SQL treats
NULL:NULLmeans "unknown or not yet priced", never zero, and different aggregate functions handleNULLrows differently.Compare `COUNT(*)` and `COUNT(amount)`
In SQL,
COUNT(*)counts rows in each group regardless of what is inside their columns. By contrast,COUNT(amount)counts non-NULLvalues of theamountcolumn:Customer 30's single order: (order_id=505, customer_id=30, order_date='2025-03-15', amount=NULL) -> COUNT(*) sees 1 row => 1 -> COUNT(amount) sees 0 non-NULL vals => 0Because of this rule,
COUNT(*) - COUNT(amount)immediately tells you how many orders for that customer are missing a dollar amount.-- COUNT(*) counts every order row, whereas COUNT(amount) skips rows where amount is NULL COUNT(*) AS order_count, COUNT(amount) AS amount_count,Compute `SUM` and `AVG` without turning unknown into zero
Every column aggregate in standard SQL (
COUNT(col),SUM(col),AVG(col),MIN(col),MAX(col)) skipsNULLinputs automatically:SUM(amount)adds up only the non-NULLamounts. If a customer has zero non-NULLamounts (like customer30in Example 1),SUM(amount)returnsNULL— not0— signaling that the customer's total spend is unknown rather than zero.AVG(amount)dividesSUM(amount)byCOUNT(amount), not byCOUNT(*). In Example 1, customer10has three orders with amounts45.00,NULL, and75.00, soAVG(amount)computes(45.00 + 75.00) / 2 = 60.0, whereas dividing by all 3 orders would treat the missing value as0.00and report40.0.ROUND(AVG(amount), 4)rounds numeric averages to 4 decimal places while preservingNULL(ROUND(NULL, 4)evaluates toNULL).
-- SUM and AVG ignore NULLs; if all amounts for a customer are NULL, both stay NULL (not 0) SUM(amount) AS total_amount, ROUND(AVG(amount), 4) AS avg_amount,Find the earliest and latest order dates
Each aggregate only ignores
NULLs in the column passed to it. BecauseMIN(order_date)andMAX(order_date)look atorder_daterather thanamount, orders withamount IS NULLstill count toward a customer's date span:- Customer
30's single order (2025-03-15,amount = NULL) still sets bothfirst_order_dateandlast_order_dateto'2025-03-15', and in Example 2 order601(2025-04-02,amount = NULL) sets customer40'sfirst_order_date. - Because ISO dates (
'YYYY-MM-DD') place year, month, and day from most significant to least significant,MINandMAXfind the true earliest and latest calendar dates whether the engine storesDATEnatively or as text (as SQLite does).
-- MIN and MAX examine order_date across all orders, even when amount is NULL MIN(order_date) AS first_order_date, MAX(order_date) AS last_order_date- Customer
Group by customer and trace Example 1
Finally,
FROM orders GROUP BY customer_idbuckets all order rows by customer before running our six aggregates. Tracing Example 1 row by row shows how all three customers behave:Input orders grouped by customer_id: customer 10: (2025-03-04, 45.00), (2025-03-12, NULL), (2025-03-19, 75.00) customer 20: (2025-03-08, 64.50) customer 30: (2025-03-15, NULL) Output rows: customer_id order_count amount_count total_amount avg_amount first_order_date last_order_date 10 3 2 120.0 60.0 2025-03-04 2025-03-19 20 1 1 64.5 64.5 2025-03-08 2025-03-08 30 1 0 NULL NULL 2025-03-15 2025-03-15Complete query
Putting everything together gives the clean ANSI SQL / SQLite query:
-- Summarize order activity per customer while preserving SQL's exact NULL semantics SELECT customer_id, -- COUNT(*) counts every order row, whereas COUNT(amount) skips rows where amount is NULL COUNT(*) AS order_count, COUNT(amount) AS amount_count, -- SUM and AVG ignore NULLs; if all amounts for a customer are NULL, both stay NULL (not 0) SUM(amount) AS total_amount, ROUND(AVG(amount), 4) AS avg_amount, -- MIN and MAX examine order_date across all orders, even when amount is NULL MIN(order_date) AS first_order_date, MAX(order_date) AS last_order_date FROM orders -- One output row per distinct customer present in the orders table GROUP BY customer_id✅ Submit now — all tests should pass.
Intuition & how it works
Imagine sorting paper purchase receipts into one folder per customer, where an occasional receipt has an unsettled, blank total (NULL). If someone asks how many orders are in a customer's folder, you count every slip of paper (COUNT(*)). If they ask how many priced orders are on file, you count only the slips with a printed total (COUNT(amount)). And if they ask for the customer's average order size, you add up the printed totals and divide by the number of priced slips — never treating an unsettled receipt as a 0.00 order.
A common beginner mistake is computing averages manually as SUM(amount) / COUNT(*) or wrapping COALESCE(amount, 0) (a function that returns its first non-NULL argument, turning NULL into 0) inside SUM and AVG. Doing that silently rewrites "this order has no price yet" into "this order cost zero", which artificially lowers a customer's average spend and reports 0 instead of NULL when every order for a customer is missing an amount.
SQL's built-in aggregate functions — functions like COUNT, SUM, AVG, MIN, and MAX that collapse a group of rows into a single summary value — follow one consistent rule: every column aggregate ignores NULLs in its target column, while only COUNT(*) counts whole rows. Take customer 10 from Example 1 with three orders: (2025-03-04, 45.00), (2025-03-12, NULL), and (2025-03-19, 75.00):
COUNT(*)counts all 3 rows ->3.COUNT(amount)counts the 2 non-NULLamounts (45.00and75.00) ->2.SUM(amount)adds45.00 + 75.00->120.0, andAVG(amount)divides120.0 / 2->60.0.MIN(order_date)andMAX(order_date)inspectorder_dateacross all 3 rows ->'2025-03-04'and'2025-03-19'.
Complexity
Let N be the number of rows in orders and C be the number of distinct customer_id values (C <= N).
- Time: Scanning
ordersonce and maintaining per-customer totals with hash aggregation (grouping rows in an in-memory hash table keyed bycustomer_id) runs inO(N)expected time; if the query planner sorts bycustomer_idinstead, it takesO(N log N)time. - Space:
O(C)memory to store the running counts, sum, min date, and max date for each distinct customer.
Indexing: A composite index on orders(customer_id, order_date, amount) acts as a covering index (an index that holds every column needed by the query so the database never has to look up the underlying table pages). Because rows in that B-tree are already ordered by customer_id, the database can stream through the index and emit one group at a time in O(1) working memory.
Edge cases
- All amounts for a customer are
NULL:order_countreflects how many orders they placed,amount_countis0, and bothtotal_amountandavg_amountevaluate toNULL(not0), as seen for customer30in Example 1. - Mix of
NULLand real amounts:AVG(amount)divides only byamount_count, soNULLrows never drag the average toward zero. - Zero-dollar orders (
amount = 0):0is a known number, notNULL, so in Example 2 order602(0.00) incrementsamount_count, contributes0tototal_amount, and pullsavg_amountto33.3333. - Negative amounts (refunds or adjustments): Included directly in
amount_count,SUM(amount), andAVG(amount)unless business rules explicitly filter them out. - Dates on
NULL-amount rows: An order withamount IS NULLstill setsfirst_order_dateorlast_order_dateif itsorder_dateis the earliest or latest for that customer (as order601does in Example 2). - Empty
orderstable:GROUP BY customer_idover zero input rows returns zero output rows.
Common mistakes
- Assuming
COUNT(amount)equalsCOUNT(*): Wheneveramountcan beNULL,COUNT(amount)is smaller by the exact number ofNULLrows. - Hand-coding
SUM(amount) / COUNT(*)for the average: Divides by orders with missing amounts, understating the true average of priced orders. - Wrapping
COALESCE(amount, 0)insideSUMorAVG: Turns unknown prices into zero, changingNULLtotals to0and shrinkingAVG. - Rounding before averaging (
AVG(ROUND(amount, 4))): Rounding individual rows does not guarantee the final mean is rounded to 4 decimals; always wrapROUNDaroundAVG(amount). - Integer division when writing custom averages: In PostgreSQL and SQLite, dividing two integers truncates decimals (
5 / 2 = 2); built-inAVG(amount)avoids integer truncation automatically.
Follow-up questions
- How would you include registered customers with zero orders and audit header amounts against an order line-items table? Start from
customersandLEFT JOINorders(keeping every registered customer while padding unmatched order columns withNULL), usingCOUNT(o.order_id)andCOALESCE(SUM(o.amount), 0)when business reporting calls for zero-order accounts to display0rather thanNULL(FULL OUTER JOINadditionally surfaces orphan orders missing acustomersrow). To auditorders.amountagainst anorder_items(order_id, qty, price)detail table, never compare grand table totals alone — offsetting errors cancel out — instead aggregateSUM(qty * price)perorder_idinside a Common Table Expression (CTE) (WITHsubquery) and flag any order whose header or item sum isNULLor differs beyond rounding tolerance:
WITH item_totals AS (
SELECT order_id, SUM(qty * price) AS items_total
FROM order_items
GROUP BY order_id
)
SELECT o.order_id, o.amount, t.items_total
FROM orders AS o
LEFT JOIN item_totals AS t ON t.order_id = o.order_id
WHERE o.amount IS NULL
OR t.items_total IS NULL
OR ABS(o.amount - t.items_total) > 0.005;
- How do UNION and UNION ALL differ when merging multi-channel order feeds, and how would you deduplicate rows or rank top spenders with window functions?
UNION ALLappends two tables (such as online and in-store feeds) verbatim inO(N)streaming time without removing duplicates, whereasUNIONhashes or sorts rows to eliminate exact duplicates (and to find IDs appearing in both feeds withoutINTERSECT, filter withWHERE EXISTS (...)). When deduplicating at read time while keeping extra metadata columns — or permanently deleting duplicate ingestions inside a transaction via physical row locators (rowidin SQLite,ctidin PostgreSQL) — use a window function (a calculation across aPARTITION BYslice that keeps individual rows intact):ROW_NUMBER() OVER (PARTITION BY order_id, customer_id, amount ORDER BY rowid)keepsrn = 1, whileDENSE_RANK() OVER (ORDER BY monthly_spend DESC)ranks top spenders or finds the Nth highest distinct value without rank gaps on ties.
WITH ranked_orders AS (
SELECT
customer_id,
order_id,
amount,
ROW_NUMBER() OVER (
PARTITION BY customer_id
ORDER BY amount DESC, order_id ASC
) AS rn,
SUM(amount) OVER (
PARTITION BY customer_id
ORDER BY order_date, order_id
) AS running_spend
FROM orders
WHERE amount IS NOT NULL
)
SELECT customer_id, order_id, amount, running_spend
FROM ranked_orders
WHERE rn = 1;
- How do relational joins, index-based joins, and row stacking translate to pandas merge, join, and concat? Use
DataFrame.mergefor SQL-style key joins (passingvalidate=to catch unexpected duplicate keys early andindicator=Trueto isolate unmatched keys),.joinwhen aligning two DataFrames on their indexes, andpd.concatwhen stacking compatible tables vertically (axis=0) or side by side (axis=1):
# Left-join spend_df onto accounts_df by key with cardinality validation
left_merged = accounts_df.merge(spend_df, on="customer_id", how="left", validate="one_to_one")
# Isolate customer_ids present only in spend_df (anti-join on the right side)
only_in_spend = (
accounts_df.merge(spend_df, on="customer_id", how="right", indicator=True)
.loc[lambda d: d["_merge"] == "right_only", ["customer_id", "spend"]]
)
# Stack two compatible order batches vertically with a fresh 0..N-1 index
combined_batches = pd.concat([orders_q1, orders_q2], axis=0, ignore_index=True)
# Join directly on DataFrame indexes rather than an explicit column
index_aligned = accounts_df.set_index("customer_id").join(
spend_df.set_index("customer_id"), how="left"
)
Follow-up questions
- How would you include registered customers with zero orders and audit header amounts against an order line-items table?
- How do UNION and UNION ALL differ when merging multi-channel order feeds, and how would you deduplicate rows or rank top spenders with window functions?
- How do relational joins, index-based joins, and row stacking translate to pandas merge, join, and concat?
Similar questions
- SQL Aggregations, Joins, Pandas Combines, and Nth Highest Salary
- Fannie Mae Mission, Testing Layers, and Validating UI Updates
- Job Posting Engagement Metrics Excluding Non-Viewing Applicants
- Compute 7-Day DAU, D1 Retention, and Revenue Cohorts
- Class-Level 2024 Exam Summary with Zero-Filled Averages
- Summarizing Imaging Claims Spend and Fiscal Months