creating a table in a DB in SQL with age groups

Viewed 24

I'm creating a DB in SQL and I need a column that that has age groups and the value to be inserted is 20-30, 31-40 ect. I have done a bit of research and cant dind an answer to what data type i should use for storing numbers with a dash in them. TIA

3 Answers

If you consider an age group just to be a sequence of characters (a name), you can use a VARCHAR.

However, if you want to use the age group for sorting, you'll have to left-pad each number to the number of digits of the used maximum value. E. g. you'd store '05-09' instead of '5-9' because values will be compared character by character, that is '5-9' > '10-20' (because 5 > 1) but '05-09' < '10-20' (because 0 < 1).

If you need access to the boundaries (numbers) of the age-groups or if you want to store additional information about the groups, you'll want to introduce a table that contains the information for each age-group. In general, you also want to reference this table using a foreign key, but it depends a bit on the use case.

I'd use varchar or nvarchar. For data integrity, you should make a foreign key reference to another table that stores all of the possible values that could be entered for the column.

I'm not recommend to create such column, because people age growth with time, so you will need to recalculate this data each day. For prevent this you can calculate age group on select. Below query generate age group on select. You can match it on your RBBMS version:

select 
    * ,
    ((date_part('year', age(birthdate))::int / 10) * 10)::varchar || ' - ' ||
    (((date_part('year', age(birthdate))::int / 10) * 10 ) + 9)::varchar age_group
from users; 

SQL online editor

Result:

+====+======+============+===========+
| id | name | birthdate  | age_group |
+====+======+============+===========+
| 1  | U1   | 1982-02-03 | 40 - 49   |
+----+------+------------+-----------+
| 3  | U3   | 2002-03-04 | 20 - 29   |
+----+------+------------+-----------+
| 2  | U2   | 1956-06-07 | 60 - 69   |
+----+------+------------+-----------+
Related