Search code examples
sqlbucketdiscrete

How to create new bucketed column from an existing continuous column in SQL?


I have the following my_table in SQL with one numeric column:

Age
---
31
53
52
37
57
19
20
63
59

I want to have a new column in the table with range buckets along the following: "Young": 0-30 "MidAge": 31-50 "Old": 51-

So the expected result:

Age AgeGroup
------------
31  MidAge
53  Old
52  Old
37  MidAge
57  Old
19  Young
20  Young
63  Old
59  Old

How can I solve it with SQL?


Solution

  • We can use a CASE expression here:

    SELECT Age, CASE WHEN Age <= 30 THEN 'Young'
                     WHEN Age <= 50 THEN 'MidAge'
                                    ELSE 'Old'
                END AS AgeGroup
    FROM yourTable;