MediumSQL challenge #108CASE WHENGROUP BYConditional Aggregation

Calculate Payment Success Rate per Method with CASE WHEN

For each payment method, show transactions, successful payments, success rate and revenue.

The challenge runs on the SQLabHub practice database (SQLite) and uses the payments table. You can solve it in the browser, with nothing to install.

Solve This SQL Challenge

Why this question comes up

The payments team is reviewing which payment providers to keep. A method that handles a lot of money but fails often costs the store sales at checkout, so they need the volume, the success rate and the money actually collected for each method.

The task

Analyze payment methods: show transaction count, success rate (%), total revenue per method.

A correct answer returns 8 rows with 5 columns: method, total_transactions, successful, success_rate_pct, revenue.

Tables used in this challenge

payments 207 rows

id INTEGER (PK) · order_id INTEGER · user_id INTEGER · amount REAL · method TEXT · status TEXT · paid_at TEXT · transaction_id TEXT

First 3 rows of the payments table
idorder_iduser_idamountmethodstatuspaid_attransaction_id
12810.52Apple Paysuccess2024-03-15TXNPTNV0A8A1
23136181.19Debit Cardsuccess2023-02-15TXNZAMXH61A0
34115114.95Debit Cardsuccess2022-01-10TXN1PVXYJS9D

The first rows of each table are shown. See how all the tables relate on the database schema page.

Expected output

Expected output of the challenge
methodtotal_transactionssuccessfulsuccess_rate_pctrevenue
PayPal40205018435.36
Credit Card463167.413434.16
Debit Card311858.110973.25
Cryptocurrency141071.46649.59
Google Pay221568.25247.02
Bank Transfer191157.94572.94
Gift Card191578.94362.01
Apple Pay161168.83978.6

The complete result: 8 rows. This is the output of the model solution on the practice database.

What you practise

  • Summarising many rows into one value with COUNT, SUM, AVG, MIN or MAX
  • Grouping rows with GROUP BY to get one result row per group
  • Turning conditions into values with CASE WHEN
  • Sorting the result with ORDER BY

Hint and approach

Try the challenge first. Open these only when you need them.

Show the hint

Use CASE WHEN inside SUM/COUNT for conditional aggregation

Show the step-by-step approach

How the model solution is built, in the order the database evaluates it:

  1. Read from the payments table.
  2. Group the rows by method, so the result has one row for each value.
  3. For each group, compute COUNT(*), a conditional count (SUM(CASE WHEN … THEN 1 ELSE 0 END)) of the rows where status equals 'success' and a conditional sum of amount over the rows where status equals 'success'.
  4. ROUND() trims the calculated figures to a fixed number of decimals.
  5. Sort the result by revenue descending.
Show the model solution
SELECT method,
       COUNT(*) AS total_transactions,
       SUM(CASE WHEN status='success' THEN 1 ELSE 0 END) AS successful,
       ROUND(100.0 * SUM(CASE WHEN status='success' THEN 1 ELSE 0 END) / COUNT(*), 1) AS success_rate_pct,
       ROUND(SUM(CASE WHEN status='success' THEN amount ELSE 0 END), 2) AS revenue
FROM payments
GROUP BY method
ORDER BY revenue DESC;

This query produced the expected output above. Yours does not have to match it word for word: any query that returns the same rows is correct.

What to watch for

Multiplying by 100.0 rather than 100 forces decimal division; with integers, SQLite would truncate every rate to a whole number. Putting the status test inside SUM(CASE ...) keeps failed payments in the denominator, which a WHERE filter would remove.

  • GROUP BY. Every selected column must either be in GROUP BY or sit inside an aggregate. SQLite accepts other columns and returns an arbitrary value for them; most databases raise an error.
  • CASE WHEN. CASE stops at the first WHEN that is true, so overlapping conditions must be ordered from most to least specific. Without an ELSE, unmatched rows get NULL.
  • ORDER BY. Without ORDER BY the row order is not guaranteed, even if it looks stable. Rows that tie on the sort columns can come back in any order.

Another way to solve it

The FILTER clause, from the SQL standard, attaches a condition to one aggregate. It reads more directly than SUM(CASE WHEN ...) and works in SQLite 3.30+ and PostgreSQL, but not in MySQL or SQL Server, where CASE is the portable form.

Show the alternative query
SELECT method,
       COUNT(*) AS total_transactions,
       COUNT(*) FILTER (WHERE status = 'success') AS successful,
       ROUND(100.0 * COUNT(*) FILTER (WHERE status = 'success') / COUNT(*), 1) AS success_rate_pct,
       ROUND(COALESCE(SUM(amount) FILTER (WHERE status = 'success'), 0), 2) AS revenue
FROM payments
GROUP BY method
ORDER BY revenue DESC;

Checked when this page was built: it returns the same rows as the model solution on the practice database.

Solve This SQL Challenge

Keep learning