01 / 21

Creating Flags
& Buckets in SQL

Learn how to categorize data by creating binary flags and range-based buckets from numeric and date fields using CASE expressions.

SQL

What Is a Flag?

A flag is a new column that holds a binary value: it is either 1 (true) or 0 (false). Flags answer simple yes/no questions about each row.

1 (True)
The row meets the condition: e.g., order total \( > \$100 \)
0 (False)
The row does not meet the condition

What Is a Bucket?

A bucket (also called a bin) groups rows into named categories based on ranges of a numeric or date value. Instead of two outcomes, buckets can have many categories.

Low Medium High VIP
\(\$0 - \$50\)
\(\$51 - \$200\)
\(\$201 - \$500\)
\(\$500+\)
Order Total Ranges

Why Do Flags & Buckets Matter?

Raw numbers are hard to summarize. Flags and buckets let you transform continuous data into categories, which makes grouping, filtering, and reporting much easier.

Simplify Analysis
Group thousands of rows into a handful of meaningful categories
Power Reports
Count how many rows fall in each bucket using GROUP BY
Enable Filtering
Quickly filter on the flag or bucket in a WHERE clause

The Core Tool: CASE Expression

Both flags and buckets are built using the SQL CASE expression. It evaluates conditions in order and returns the first matching result.

CASE WHEN condition_1 THEN result_1 WHEN condition_2 THEN result_2 ... ELSE default_result END

The Flag Pattern

A flag uses CASE with a single condition. It returns 1 when the condition is true and 0 otherwise.

SELECT order_id, total, CASE WHEN total > 100 THEN 1 ELSE 0 END AS is_high_value FROM orders;

The Bucket Pattern

A bucket uses CASE with multiple conditions, each defining a range. The conditions must be ordered carefully so ranges don't overlap.

SELECT order_id, total, CASE WHEN total < 50 THEN 'Low' WHEN total < 200 THEN 'Medium' WHEN total < 500 THEN 'High' ELSE 'VIP' END AS spend_tier FROM orders;

Flags vs. Buckets

Flag Bucket
Possible values 2 (\(0\) or \(1\)) Many (named categories)
Number of WHEN clauses 1 2 or more
Output data type Integer (0/1) Text (string labels)
Best used for Counting, filtering Grouping, reporting
Example question "Is this order high-value?" "What tier is this order?"

Step-by-Step Approach

1
Identify the source column: Which numeric or date field will drive the categorization?
2
Decide: flag or bucket? If you only need yes/no, use a flag. If you need multiple categories, use a bucket.
3
Define boundaries: Write out the exact thresholds. Ensure ranges are mutually exclusive and collectively exhaustive.
4
Write the CASE: Order your WHEN clauses from smallest to largest. Always include an ELSE clause.
5
Alias the result: Give the new column a clear, descriptive name using AS.

Example: Date-Based Flag

Flag all users who signed up in the last \(30\) days as "new users."

SELECT user_id, signup_date, CASE WHEN signup_date >= CURRENT_DATE - 30 THEN 1 ELSE 0 END AS is_new_user FROM users;

Example: Date-Based Bucket

Categorize users by account age into tenure buckets.

SELECT user_id, signup_date, CASE WHEN signup_date >= CURRENT_DATE - 30 THEN 'New (0-30 days)' WHEN signup_date >= CURRENT_DATE - 90 THEN 'Recent (31-90 days)' WHEN signup_date >= CURRENT_DATE - 365 THEN 'Established (91-365 days)' ELSE 'Veteran (1+ year)' END AS tenure_bucket FROM users;

Using Flags with Aggregation

Since flags are \(0\)s and \(1\)s, you can use SUM and AVG on them to get counts and percentages.

SELECT SUM(CASE WHEN total > 100 THEN 1 ELSE 0 END) AS high_value_count, AVG(CASE WHEN total > 100 THEN 1.0 ELSE 0 END) AS high_value_pct FROM orders;

Using Buckets with GROUP BY

Buckets become truly powerful when you GROUP BY the bucket column to get aggregate stats per category.

SELECT CASE WHEN age < 18 THEN 'Minor' WHEN age < 30 THEN 'Young Adult' WHEN age < 50 THEN 'Adult' ELSE 'Senior' END AS age_group, COUNT(*) AS num_users, AVG(total_spent) AS avg_spent FROM users GROUP BY age_group;

Advanced: Multiple Flags

You can create several flags at once in the same SELECT. Each CASE expression becomes its own column.

SELECT order_id, CASE WHEN total > 100 THEN 1 ELSE 0 END AS is_high_value, CASE WHEN discount > 0 THEN 1 ELSE 0 END AS has_discount, CASE WHEN shipped_date IS NOT NULL THEN 1 ELSE 0 END AS is_shipped FROM orders;

Common Mistakes

✕ Forgetting ELSE
Without ELSE, unmatched rows get NULL instead of \(0\). Always include ELSE 0 for flags and ELSE 'Other' for buckets.
✕ Overlapping Ranges
Using \(\ge 50\) AND \(\le 100\) on one WHEN and \(\ge 100\) on the next creates ambiguity at the boundary. Use strictly ordered \(\lt\) comparisons.
✕ Wrong WHEN Order
Putting the broadest condition first catches everything. For buckets, always check from smallest to largest (or most recent to oldest for dates).

Summary Reference

Pattern Key Detail
Flag CASE WHEN ... THEN 1 ELSE 0 END Binary: \(0\) or \(1\)
Bucket CASE WHEN ... THEN 'label' ... END Multiple string categories
Date flag WHEN col >= CURRENT_DATE - N Use date arithmetic
Date bucket Check most recent first Order: recent to oldest
SUM(flag) Counts true rows Works because \(1+1+0 = 2\)
AVG(flag) Percentage of true Use 1.0 to avoid integer division
GROUP BY bucket Distribution report One row per category

Question 1 of 5

What does a flag column typically contain?

Question 2 of 5

Given this SQL fragment, what label does an order with total = 150 receive?

CASE WHEN total < 50 THEN 'Low' WHEN total < 200 THEN 'Medium' WHEN total < 500 THEN 'High' ELSE 'VIP' END

Question 3 of 5

What happens if you write a CASE expression without an ELSE clause and no WHEN condition matches?

Question 4 of 5

If you wrap a flag in SUM(), what does the result represent?

Question 5 of 5

You want to bucket users by signup date, checking the most recent dates first. Why is this order important?