Skip to content
Advertisement

Using if-then or case-when-then to select from dataset

I have a dataset with students in 1st, 2nd and 3rd grades. I want to select the names of all students in 1st and 2nd grades, but only students named John, Jane or Smith from 3rd grade. Here is what I have so far:

select 
first_name, 
grade_level

from table_with_all_students_info

-- I need an if or case when statement here saying if student is in third grade, their first name selected can only be John, Jane or Smith. My attempt is below. 

case when grade_level in ('3rd grade')
then first_name in ('John', 'Jane', 'Smith')

I’m not sure what I’m getting wrong there but I’d appreciate some help. Thanks

Advertisement

Answer

You can UNION two queries such as this:

    select first_name, grade_level
    from table
    where grade_level in ('1st','2nd')
    union
    select first_name, grade_level
    from table
    where grade_level = '3rd'
    and first_name in ('John','Jane','Smith')
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement