SQL beginner case when categorization revenue

How to Categorize Revenue Using SQL CASE WHEN?

Categorize Revenue Tiers is a SQL query that this sql query categorizes revenue into 'low', 'medium', and 'high' tiers based on specified thresholds.. Formula Genius generates and validates this formula automatically from a plain-English prompt.

Using SQL's CASE WHEN statement allows you to easily categorize revenue into defined tiers, enhancing data analysis and reporting.

The Formula

Prompt

"Categorize revenue into 'Low', 'Medium', 'High' tiers using CASE WHEN inside a SELECT"

SQL
SELECT revenue, CASE WHEN revenue < 1000 THEN 'Low' WHEN revenue BETWEEN 1000 AND 5000 THEN 'Medium' ELSE 'High' END AS revenue_tier FROM sales;

This SQL query categorizes revenue into 'Low', 'Medium', and 'High' tiers based on specified thresholds.

Step-by-Step Breakdown

  1. Step 1: Select the revenue column from the sales table.
  2. Step 2: Use the CASE WHEN statement to define conditions for categorization.
  3. Step 3: Specify the threshold for 'Low' revenue (< 1000).
  4. Step 4: Define the range for 'Medium' revenue (1000 to 5000).
  5. Step 5: Assign 'High' revenue for all values above 5000.

Edge Cases & Warnings

  • Revenue exactly at the threshold (1000 or 5000) may cause confusion in categorization.
  • Negative revenue values should be handled appropriately, possibly categorized as 'Low'.
  • Null revenue values need to be considered to avoid incorrect categorization.

Examples

Prompt

"Revenue of 500"

SQL
'Low'
Prompt

"Revenue of 3000"

SQL
'Medium'

Frequently Asked Questions

What is the purpose of the CASE WHEN statement?

It allows for conditional logic in SQL queries to categorize data.

Can I add more tiers to the categorization?

Yes, you can add more WHEN clauses for additional categories.

How do I handle NULL values in revenue?

You can add an additional condition in the CASE statement to check for NULL values.

Can't find what you need?

Describe any formula in plain English and Formula Genius will generate, explain, and validate it — instantly.