1

I have table with column data_of_birth. I want to create query where people between 0-10 will be A, and 11-18 will be B. Something like this :

+-------+-----+-------+
| name  | age | class |
+-------+-----+-------+
| betty |   9 | A     |
| carl  |  12 | B     |
+-------+-----+-------+

The problem is how to create last column with dynamic data ?

2
  • 2
    Hint: CASE expression. Commented Jan 17, 2020 at 17:43
  • oki, i will try ;p Commented Jan 17, 2020 at 17:44

1 Answer 1

1

As hinted by Gordon Linoff, you can use a case expression:

select 
    name,
    age,
    case
        when age between 0 and 10 then 'A'
        when age between 11 and 18 then 'B'
        else '?'
    end class
from mytable 

Note: age is the name of a built-in Postgres date/time function, so this is not a good pick for a column name.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for answer, it was really helpfull. I have another question it is good solution when i'm using this function 3 times in one query? extract(YEAR from age( timestamp '2019-12-01' , date_of_birth))
@JarekSularz That's another question. Please accept this answer, and create a new one.
@JarekSularz: very likely, your database will optimize the expression and not compute it 3 times, so that should not be an issue.
Thanks a lot and have a nice evening ;p

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.