How do you count successes and unknowns in one query?
Question
For each plan, return the number of attempts, successes, and attempts whose outcome is unknown. A NULL outcome means unknown, and it still counts as an attempt. Sort by plan.
attempts
| plan | outcome |
|---|---|
| basic | success |
| basic | failed |
| basic | NULL |
| pro | failed |
| pro | failed |
| team | NULL |
Show hints (2)
- "START WITH EVERY ROW"
Every row is an attempt. An aggregate that counts only known outcome values would miss some.
- "FILTER EACH AGGREGATE"
Apply a separate condition to the success and unknown counts.
Show checked explanation
Use COUNT(*) for attempts. Add FILTER to count success and NULL outcomes from the same groups.
SELECT plan, COUNT(*) AS attempts, COUNT(*) FILTER (WHERE outcome = 'success') AS successes, COUNT(*) FILTER (WHERE outcome IS NULL) AS unknowns FROM attempts GROUP BY plan ORDER BY plan;
plan | attempts | successes | unknowns basic | 3 | 1 | 1 pro | 2 | 0 | 0 team | 1 | 0 | 1
Ran the query on SQLite 3.49 with the sample rows and edge cases.
Walkthrough
Basic has three rows, including one without an outcome. The success filter sees one row and the unknown filter sees one. The Pro success count is zero. Team still has one attempt because the total counts rows regardless of outcome.
Common mistakes
- Using
COUNT(outcome)as the total and dropping the unknown outcomes. - Putting
outcome = 'success'in the query'sWHERE, removing failed plans from the report. - Using
COUNT(outcome) FILTER (WHERE outcome IS NULL). The count skips every null row that passes the filter.
Follow-up questions
- "How do you write the success count without FILTER?" Use
SUM(CASE WHEN outcome = 'success' THEN 1 ELSE 0 END)for groups with input rows. - "What is the success share among known outcomes for Basic?" One of the two known outcomes is a success, so the share is 0.5. Use decimal division and handle groups with zero known outcomes.
What a strong answer covers
Name the denominator clearly and show which rows are included in each aggregate.
Open in interactive practice deck →