Skip to content
Quantoros

Bucket customers into bands - Prime (750+), Near-prime (650-749), Unscored (NULL score), Subprime (everything else) -…

SQLLevel: FoundationCASE WHEN

Bucket customers into bands - Prime (750+), Near-prime (650-749), Unscored (NULL score), Subprime (everything else) - and count customers per band.

Table definitions (from the source exercise):

CREATE TABLE customers(customer_id INTEGER PRIMARY KEY, name TEXT, city TEXT, signup_date TEXT, credit_score INTEGER);
Hints
  • Distinguish a missing value from zero, an empty string and false.
  • Test comparison, aggregation and filtering on a tiny missing-value example.

Answer

Approach: CASE WHEN checks run top-down; test IS NULL before the numeric comparisons or put it in its own branch.

SELECT CASE WHEN credit_score >= 750 THEN 'Prime'
            WHEN credit_score >= 650 THEN 'Near-prime'
            WHEN credit_score IS NULL THEN 'Unscored'
            ELSE 'Subprime' END AS band,
       COUNT(*) AS num_customers
FROM customers
GROUP BY band;

The source uses SQLite with a MySQL compatibility layer. Date and string functions are dialect dependent; the query is preserved as published.

Source and licence: SQL Practice Lab — Ebrahim Sharifi · MIT

Related questions