Cumulative Loss Projection Across Policy Renewals
SQL & DataAuto-gradedLast updated
Compute the projected total loss from each policy renewal onward, summing the current period's loss with all subsequent renewal periods.
You are analyzing insurance policy renewal data. Each policy can renew multiple times, and each renewal period records the loss incurred during that period.
For each renewal period, calculate the projected cumulative loss: the sum of losses starting from that period through all later renewals of the same policy.
You have the following table structure:
CREATE TABLE policy_term_losses (
policy_id VARCHAR, -- Policy identifier
term_id VARCHAR, -- Renewal period identifier
term_sequence INTEGER, -- Chronological position (higher = later)
term_start_date DATE,
term_end_date DATE,
loss_amount DECIMAL(18, 2) -- Loss recorded in this period
);
Given constraints:
- Each
term_idis associated with exactly onepolicy_id - Within a policy,
term_sequencedefines the chronological order - Each
(policy_id, term_sequence)pair appears at most once loss_amountmay be negative (adjustments/recoveries), positive, or zero- Calculations depend on sequence order, not dates
Required output: Return all renewal periods with these columns:
policy_idterm_idterm_sequenceloss_amountprojected_cumulative_loss— sum ofloss_amountfrom this period forward
Example:
Input for policy P1:
| policy_id | term_id | term_sequence | loss_amount |
|---|---|---|---|
| P1 | T1 | 1 | 100 |
| P1 | T2 | 2 | 50 |
| P1 | T3 | 3 | 25 |
Expected output:
| policy_id | term_id | term_sequence | loss_amount | projected_cumulative_loss |
|---|---|---|---|---|
| P1 | T1 | 1 | 100 | 175 |
| P1 | T2 | 2 | 50 | 75 |
| P1 | T3 | 3 | 25 | 25 |
Write a SQL query to produce this result.
Hints
Hint 1
This is a reverse running total—start from the last period and accumulate backward.
Hint 2
Window functions with custom frame specifications can compute sums over a range relative to the current row.
Hint 3
Partition by policy so calculations don't cross policies; order matters for defining the accumulation range.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The projected cumulative loss is a reverse running total within each policy. For any renewal period, you sum its loss with every later period's loss. This maps cleanly to a window function with a carefully specified frame.
The key components:
- Partition by
policy_idto keep each policy's calculation independent - Order by
term_sequenceto establish chronological flow - Frame from current row to the end to include this period and all future periods
Window functions avoid the quadratic cost of self-joins and express the business logic directly.
SQL Solution
SELECT
policy_id,
term_id,
term_sequence,
loss_amount,
SUM(loss_amount) OVER (
PARTITION BY policy_id
ORDER BY term_sequence
ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
) AS projected_cumulative_loss
FROM policy_term_losses
ORDER BY policy_id, term_sequence;
Alternative formulation (equivalent semantics):
SUM(loss_amount) OVER (
PARTITION BY policy_id
ORDER BY term_sequence DESC
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS projected_cumulative_loss
Both produce identical results. The first form mirrors the business definition more clearly ("this period and everything after"), which often reads better in an interview setting.
Why This Works
Consider policy P1 with three periods, ordered by term_sequence:
| term_sequence | loss_amount | window frame (current → end) | projected_cumulative_loss |
|---|---|---|---|
| 1 | 100 | 100 + 50 + 25 | 175 |
| 2 | 50 | 50 + 25 | 75 |
| 3 | 25 | 25 | 25 |
- Partitioning ensures losses from different policies never mix
- Ordering by
term_sequencerespects the given chronological order—we use the sequence number rather than dates because sequences are the authoritative ordering mechanism - The frame specification captures exactly the rows where
term_sequence >= current_sequence, matching the definition
Why Use ROWS Instead of the Default?
If you omit ROWS and write just ORDER BY term_sequence, the default frame is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW. With RANGE, rows with tied sort keys are treated as peers and summed together.
In this case, uniqueness guarantees no ties, so the default would still work. However, explicitly specifying ROWS is better practice:
- Declares intent clearly
- Prevents subtle bugs if uniqueness assumptions change
- Can improve performance on some engines (e.g., SQL Server), as
RANGEmay require additional sorting/buffering
Interviewers often probe this distinction to assess depth of SQL knowledge.
Complexity
- Time: O(n log n) for sorting rows within partitions, followed by a linear pass for the windowed sum. If an index exists on
(policy_id, term_sequence), the sort is skipped and execution is O(n). - Space: O(n) for the result set, plus engine-specific overhead for partitioning/sorting.
Naive alternative (self-join):
SELECT t1.policy_id, t1.term_id, t1.term_sequence, t1.loss_amount,
SUM(t2.loss_amount) AS projected_cumulative_loss
FROM policy_term_losses t1
JOIN policy_term_losses t2
ON t2.policy_id = t1.policy_id
AND t2.term_sequence >= t1.term_sequence
GROUP BY t1.policy_id, t1.term_id, t1.term_sequence, t1.loss_amount;
This self-join costs O(k²) per policy with k periods. It works on older databases without window function support, but you should acknowledge the performance trade-off.
Edge Cases
- Negative or zero losses: These represent adjustments (recoveries, salvage, corrections). Standard summation handles them correctly; the projected cumulative loss can be negative. Do not filter or take absolute values.
- Single-period policy: The projected loss equals that period's loss.
- Non-consecutive
term_sequencevalues (e.g., 1, 2, 5): Logic still works because it depends on relative order, not consecutive numbering. - NULL
loss_amount:SUMignores NULLs by default. If all values in a frame are NULL, the result is NULL. If business logic treats missing losses as zero, useSUM(COALESCE(loss_amount, 0)). Clarify this assumption with the interviewer. - Precision: Use
DECIMALthroughout. Casting to floating-point types introduces rounding errors unacceptable for financial data. - Output order: Window functions don't guarantee final result order. Add explicit
ORDER BYif ordering matters to consumers.
Python (pandas) Alternative
Since technical screens may accept Python, here's the pandas equivalent. Sort each policy's periods in reverse chronological order, then compute a grouped cumulative sum:
import pandas as pd
def projected_cumulative_loss(df: pd.DataFrame) -> pd.DataFrame:
"""
Compute projected cumulative loss for each policy period.
Args:
df: DataFrame with columns policy_id, term_id, term_sequence, loss_amount
Returns:
DataFrame with original columns plus projected_cumulative_loss,
sorted by policy_id and term_sequence.
"""
result = df[["policy_id", "term_id", "term_sequence", "loss_amount"]].copy()
# Sort in reverse chronological order within each policy
result = result.sort_values(
["policy_id", "term_sequence"],
ascending=[True, False]
)
# Cumulative sum within each policy group
result["projected_cumulative_loss"] = (
result.groupby("policy_id", sort=False)["loss_amount"]
.cumsum()
)
# Return in chronological order
return result.sort_values(
["policy_id", "term_sequence"]
).reset_index(drop=True)
# Example usage
if __name__ == "__main__":
data = pd.DataFrame({
"policy_id": ["P1", "P1", "P1"],
"term_id": ["T1", "T2", "T3"],
"term_sequence": [1, 2, 3],
"loss_amount": [100, 50, 25],
})
print(projected_cumulative_loss(data))
# projected_cumulative_loss: 175, 75, 25
Note: pandas cumsum() propagates NaN values. If missing losses should be treated as zero, apply .fillna(0) before the cumulative sum.
What Strong Candidates Demonstrate
- Pattern recognition: Immediately identify this as a reverse cumulative sum that maps to a window function with a forward-looking frame.
- Correct partitioning and ordering: Ensure totals never cross policies and sequence defines the accumulation direction.
- Explicit frame specification: Use
ROWS BETWEENand understand theROWSvsRANGEdistinction. - Domain awareness: Recognize that negative adjustments are valid business scenarios and that sequence (not dates) is the authoritative ordering.
- Clarifying questions: Ask about NULL handling and mention the performance cost of self-join alternatives when discussing trade-offs.