download

How do you count successes and unknowns in one query?

SQL~7 minReviewed 2 Dec 2026Free · No sign-in

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

planoutcome
basicsuccess
basicfailed
basicNULL
profailed
profailed
teamNULL
Show hints (2)
  1. "START WITH EVERY ROW"

    Every row is an attempt. An aggregate that counts only known outcome values would miss some.

  2. "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.

"SOLUTION · SQL"
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;
"OUTPUT"
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's WHERE, 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 →

Original OfferVibe question. SQLite aggregate functions.
© 2026 OfferVibe · Text CC BY-NC-SA 4.0 · code MITFree to share and adapt with credit, not for commercial use. Code samples are free for any use.