>_QueryLocalCSV & JSON tools that run in your browser

How do I bucket rows into categories with SQL CASE WHEN?

SELECT
  CASE WHEN quantity >= 3 THEN 'bulk' ELSE 'single' END AS order_size,
  COUNT(*) AS orders,
  SUM(quantity * unit_price) AS revenue
FROM data
GROUP BY order_size;

Run this query on the demo dataset →

CASE WHEN ... THEN ... ELSE ... END works like an inline if/else: it evaluates the condition for each row and returns one value or another, and you can use the result as if it were a real column — including grouping by it. This turns a continuous number (quantity) into a small number of labeled buckets you can then aggregate.

A table named data with columns: order_id (integer), customer (text), country (text), category (text), quantity (integer), unit_price (real), order_date (text, YYYY-MM-DD).

Want to run it on your own file? Open it with Query CSV with SQL: your file becomes the table data, and you can paste this query with your own column names.

Related recipes