Rebooking Rate After Initial Cancellation
SQL & DataAuto-gradedLast updated
Calculate what fraction of users whose earliest appointment was cancelled never scheduled another confirmed or returned appointment afterward.
You work with a dataset tracking appointment scheduling behavior.
Given a table with appointment records:
Table: appointments
appointment_id(BIGINT, primary key)user_id(BIGINT, not null)scheduled_start_at(TIMESTAMP, not null) — planned start timestatus(VARCHAR, not null) — final outcome:'cancelled','returned','confirmed','completed','no_show'status_updated_at(TIMESTAMP, not null) — timestamp when status was finalized
Rules
- Users may have multiple appointments
- A user's earliest appointment is determined by the minimum
scheduled_start_at; if multiple appointments share that timestamp, use the smallestappointment_id - A user falls into the initial cancellation cohort if their earliest appointment has
status = 'cancelled' - A user rebooked if they have any appointment with
scheduled_start_atstrictly greater than their earliest appointment's start time ANDstatus IN ('returned', 'confirmed')
Your task
Write SQL to determine what percentage of users in the initial cancellation cohort never rebooked.
Return one row with:
first_cancelled_users(integer) — total users in cohortnever_returned_confirmed_users(integer) — cohort members who never rebookedpct_never_returned_confirmed(decimal, 0 to 1) — the ratio
Use CTEs and window functions as needed.
Hints
Hint 1
Use ROW_NUMBER with a two-part ordering to identify each user's earliest appointment deterministically
Hint 2
Apply the cancelled filter after identifying the earliest appointment, not before
Hint 3
Use EXISTS or a LEFT JOIN with COUNT to check for rebooking without creating duplicate rows per user
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem requires building a cohort and then measuring an outcome within that cohort.
Step 1: Identify each user's earliest appointment
Use ROW_NUMBER() partitioned by user_id and ordered by scheduled_start_at, appointment_id. This assigns rank 1 to exactly one appointment per user, following the tie-breaking rule. Filtering to rn = 1 gives us each user's earliest appointment.
Step 2: Filter to the cohort
Keep only users whose earliest appointment has status = 'cancelled'. This is our denominator.
Step 3: Check for rebooking
For each cohort member, determine whether any appointment exists with:
- Same
user_id scheduled_start_atstrictly after the earliest appointment's start timestatus IN ('returned', 'confirmed')
Use EXISTS or a LEFT JOIN to avoid row multiplication.
Step 4: Aggregate
Count total cohort members, sum those who never rebooked, and compute the percentage with safe division.
Solution
WITH ranked AS (
SELECT
appointment_id,
user_id,
scheduled_start_at,
status,
ROW_NUMBER() OVER (
PARTITION BY user_id
ORDER BY scheduled_start_at, appointment_id
) AS rn
FROM appointments
),
initial_cancelled AS (
SELECT
user_id,
scheduled_start_at AS earliest_start
FROM ranked
WHERE rn = 1
AND status = 'cancelled'
),
outcome AS (
SELECT
ic.user_id,
CASE
WHEN EXISTS (
SELECT 1
FROM appointments a
WHERE a.user_id = ic.user_id
AND a.scheduled_start_at > ic.earliest_start
AND a.status IN ('returned', 'confirmed')
) THEN 0
ELSE 1
END AS never_rebooked
FROM initial_cancelled ic
)
SELECT
COUNT(*) AS first_cancelled_users,
COALESCE(SUM(never_rebooked), 0) AS never_returned_confirmed_users,
CAST(COALESCE(SUM(never_rebooked), 0) AS DECIMAL(10, 4))
/ NULLIF(COUNT(*), 0) AS pct_never_returned_confirmed
FROM outcome;
Why This Works
Deterministic earliest appointment: ROW_NUMBER() with the two-column ordering ensures exactly one row per user gets rank 1, even when timestamps tie.
Filter placement matters: Applying status = 'cancelled' after ranking ensures we're filtering the true earliest appointment. Filtering before ranking would incorrectly identify a user's earliest cancelled appointment as their "first," even if they had an earlier completed appointment.
No row multiplication: EXISTS returns a boolean per cohort user. A user with ten future confirmed appointments still contributes exactly one row. Using INNER JOIN without aggregation would duplicate rows and inflate counts.
Strict inequality: The > comparison correctly excludes appointments at the same timestamp. An appointment with the same scheduled_start_at but larger appointment_id is not "future."
Safe division: Casting to DECIMAL before dividing avoids integer truncation. NULLIF(COUNT(*), 0) handles the empty-cohort edge case gracefully.
Complexity
Let n = total rows in appointments, u = number of users.
- Time: O(n log n) for the window function sort. The
EXISTSsubquery runs as a semi-join; with an index on(user_id, scheduled_start_at)it's O(n) overall. Sorting dominates. - Space: O(n) for window partitioning, O(u) for cohort storage.
Critical Edge Cases
| Scenario | Handling |
|---|---|
| Multiple appointments share earliest timestamp | Smallest appointment_id wins via ORDER BY clause |
| Future appointment at same timestamp | Not counted as rebooking (strict >) |
Future completed or no_show appointment | Does not count; only returned/confirmed qualify |
| User with single cancelled appointment | Included in cohort, counted as never rebooked |
| Empty cohort | COALESCE and NULLIF prevent errors; percentage becomes NULL |
| Integer division behavior | Cast before dividing to get decimal result |
Alternative: LEFT JOIN Approach
Some prefer avoiding correlated subqueries:
outcome AS (
SELECT
ic.user_id,
CASE WHEN COUNT(a.appointment_id) = 0 THEN 1 ELSE 0 END AS never_rebooked
FROM initial_cancelled ic
LEFT JOIN appointments a
ON a.user_id = ic.user_id
AND a.scheduled_start_at > ic.earliest_start
AND a.status IN ('returned', 'confirmed')
GROUP BY ic.user_id
)
Critical: The filter conditions must be in the ON clause. Putting a.status IN (...) in a WHERE clause converts the LEFT JOIN into an inner join, silently dropping users who never rebooked.
Common Mistakes
- Using
RANK()orMIN()without full tie-breaking: Can return multiple "first" appointments per user - Filtering before ranking: Changes which appointment is considered "first"
- Using
>=instead of>: Incorrectly includes same-timestamp appointments as rebookings - Plain
INNER JOINwithout aggregation: Multiplies rows and inflates counts - Forgetting
completeddoesn't count: Onlyreturnedandconfirmedindicate rebooking intent WHEREclause in LEFT JOIN pattern: Converts to inner join, drops users without rebookings
Follow-up Variations
Interviewers often ask:
- "What if we want rebooking within 30 days?"
- "How would you segment by cancellation reason?"
- "What index would optimize this query in production?"
For the last point: a covering index on (user_id, scheduled_start_at, appointment_id) INCLUDE (status) supports both the ranking and the semi-join efficiently.