Skip to content
Advertisement

Simple SQL CASE Question – from WHERE to CASE function

Sorry for the noob question, new to SQL here and would appreciate help 🙂

I have this SQL query:

select * from nobel_win 
where (subject = 'Physiology' and year < 1971) 
and (subject = 'Peace' and year => 1974) 

Will I have the same result if I use this query? (Am I applying the case function correctly here?) If not, can someone help me fix the query below, if possible?

select * 
(case when subject = 'Physiology' and year < 1971 end),
(case when subject = 'Peace' and year => 1974 end),
from nobel_win

*EDIT

The original query actually went like this, and I tried to shorten the UNION by doing WHERE (refer to first code block). Can someone correct my first code block so that it’ll display the same output? Thanks a bunch 🙁

(select * from nobel_win
where subject = 'Physiology' and year < 1971)
UNION
(select * from nobel_win
where subject = 'Peace' and year => 1974)

Advertisement

Answer

In fact, the first version, or a slight modification of it, is likely what you want here:

SELECT *
FROM nobel_win 
WHERE
    subject = 'Physiology' AND year < 1971 OR
    subject = 'Peace' AND year >= 1974;

Note that I have ORed the two conditions together, since it is impossible for a single record to belong to more than one subject (or year). Note that CASE expressions are not for handling boolean logic, but rather they output scalar values based on certain logic.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement