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 whose amount is NULL.
  • amount_count: number of order rows for this customer that have a non-NULL amount.
  • total_amount: sum of non-NULL amount values for this customer, or NULL if none of the customer's orders have a non-NULL amount.
  • avg_amount: arithmetic mean of non-NULL amount values for this customer, rounded to 4 decimal places, or NULL if no non-NULL amount exists.
  • first_order_date: earliest order_date across all orders placed by this customer (including orders where amount is NULL).
  • last_order_date: latest order_date across all orders placed by this customer (including orders where amount is NULL).

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 10 has 3 orders in total, 2 of which carry priced amounts (45.00 and 75.00). Their sum is 120.0 and their average divides by the 2 priced rows (120.0 / 2 = 60.0), not all 3 orders.
  • Customer 20 has a single priced order of 64.50 on 2025-03-08.
  • Customer 30 has 1 order whose amount is NULL, so amount_count = 0 and both total_amount and avg_amount remain NULL, while first_order_date and last_order_date are 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_id is unique across orders; order_date is never NULL.
  • amount may be positive, 0, negative (for refunds or credits), or NULL.
  • If orders is empty, return zero rows.
  • Output row order does not matter.

Step-by-step walkthrough

  1. Restate the per-customer summary task

    Over orders(order_id, customer_id, order_date, amount), we need to return one summary row per customer_id present in orders (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 customer
    

    The core principle is how SQL treats NULL: NULL means "unknown or not yet priced", never zero, and different aggregate functions handle NULL rows differently.

  2. 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-NULL values of the amount column:

    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  => 0
    

    Because 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,
    
  3. 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)) skips NULL inputs automatically:

    • SUM(amount) adds up only the non-NULL amounts. If a customer has zero non-NULL amounts (like customer 30 in Example 1), SUM(amount) returns NULL — not 0 — signaling that the customer's total spend is unknown rather than zero.
    • AVG(amount) divides SUM(amount) by COUNT(amount), not by COUNT(*). In Example 1, customer 10 has three orders with amounts 45.00, NULL, and 75.00, so AVG(amount) computes (45.00 + 75.00) / 2 = 60.0, whereas dividing by all 3 orders would treat the missing value as 0.00 and report 40.0.
    • ROUND(AVG(amount), 4) rounds numeric averages to 4 decimal places while preserving NULL (ROUND(NULL, 4) evaluates to NULL).
        -- 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,
    
  4. Find the earliest and latest order dates

    Each aggregate only ignores NULLs in the column passed to it. Because MIN(order_date) and MAX(order_date) look at order_date rather than amount, orders with amount IS NULL still count toward a customer's date span:

    • Customer 30's single order (2025-03-15, amount = NULL) still sets both first_order_date and last_order_date to '2025-03-15', and in Example 2 order 601 (2025-04-02, amount = NULL) sets customer 40's first_order_date.
    • Because ISO dates ('YYYY-MM-DD') place year, month, and day from most significant to least significant, MIN and MAX find the true earliest and latest calendar dates whether the engine stores DATE natively 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
    
  5. Group by customer and trace Example 1

    Finally, FROM orders GROUP BY customer_id buckets 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-15
    
  6. Complete 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):

  1. COUNT(*) counts all 3 rows -> 3.
  2. COUNT(amount) counts the 2 non-NULL amounts (45.00 and 75.00) -> 2.
  3. SUM(amount) adds 45.00 + 75.00 -> 120.0, and AVG(amount) divides 120.0 / 2 -> 60.0.
  4. MIN(order_date) and MAX(order_date) inspect order_date across 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 orders once and maintaining per-customer totals with hash aggregation (grouping rows in an in-memory hash table keyed by customer_id) runs in O(N) expected time; if the query planner sorts by customer_id instead, it takes O(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_count reflects how many orders they placed, amount_count is 0, and both total_amount and avg_amount evaluate to NULL (not 0), as seen for customer 30 in Example 1.
  • Mix of NULL and real amounts: AVG(amount) divides only by amount_count, so NULL rows never drag the average toward zero.
  • Zero-dollar orders (amount = 0): 0 is a known number, not NULL, so in Example 2 order 602 (0.00) increments amount_count, contributes 0 to total_amount, and pulls avg_amount to 33.3333.
  • Negative amounts (refunds or adjustments): Included directly in amount_count, SUM(amount), and AVG(amount) unless business rules explicitly filter them out.
  • Dates on NULL-amount rows: An order with amount IS NULL still sets first_order_date or last_order_date if its order_date is the earliest or latest for that customer (as order 601 does in Example 2).
  • Empty orders table: GROUP BY customer_id over zero input rows returns zero output rows.

Common mistakes

  • Assuming COUNT(amount) equals COUNT(*): Whenever amount can be NULL, COUNT(amount) is smaller by the exact number of NULL rows.
  • 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) inside SUM or AVG: Turns unknown prices into zero, changing NULL totals to 0 and shrinking AVG.
  • Rounding before averaging (AVG(ROUND(amount, 4))): Rounding individual rows does not guarantee the final mean is rounded to 4 decimals; always wrap ROUND around AVG(amount).
  • Integer division when writing custom averages: In PostgreSQL and SQLite, dividing two integers truncates decimals (5 / 2 = 2); built-in AVG(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 customers and LEFT JOIN orders (keeping every registered customer while padding unmatched order columns with NULL), using COUNT(o.order_id) and COALESCE(SUM(o.amount), 0) when business reporting calls for zero-order accounts to display 0 rather than NULL (FULL OUTER JOIN additionally surfaces orphan orders missing a customers row). To audit orders.amount against an order_items(order_id, qty, price) detail table, never compare grand table totals alone — offsetting errors cancel out — instead aggregate SUM(qty * price) per order_id inside a Common Table Expression (CTE) (WITH subquery) and flag any order whose header or item sum is NULL or 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 ALL appends two tables (such as online and in-store feeds) verbatim in O(N) streaming time without removing duplicates, whereas UNION hashes or sorts rows to eliminate exact duplicates (and to find IDs appearing in both feeds without INTERSECT, filter with WHERE EXISTS (...)). When deduplicating at read time while keeping extra metadata columns — or permanently deleting duplicate ingestions inside a transaction via physical row locators (rowid in SQLite, ctid in PostgreSQL) — use a window function (a calculation across a PARTITION BY slice that keeps individual rows intact): ROW_NUMBER() OVER (PARTITION BY order_id, customer_id, amount ORDER BY rowid) keeps rn = 1, while DENSE_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.merge for SQL-style key joins (passing validate= to catch unexpected duplicate keys early and indicator=True to isolate unmatched keys), .join when aligning two DataFrames on their indexes, and pd.concat when 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

Similar questions

More Fannie Mae interview questions

All 3 Fannie Mae questions →