Appearance
CASE
Return specific values for different cases based on the evaluation of a series of WHEN conditions. CASE expressions take two forms: simple and searched.
Simple CASE expression:
CASE expression
WHEN value THEN result
[WHEN ...]
[ELSE result]
END
Searched CASE expression:
CASE
WHEN boolean condition THEN result
[WHEN ...]
[ELSE result]
END
Simple CASE example:
select season_name, winners,
case winners
when 'Leicester City' then 'One win'
when 'Blackburn Rovers' then 'One win'
when '' then 'Unknown'
else 'Two or more wins'
end
from season
order by 1;
season_name | winners | case
-------------+-------------------+------------------
1992-1993 | Manchester United | Two or more wins
1993-1994 | Manchester United | Two or more wins
1994-1995 | Blackburn Rovers | One win
1995-1996 | Manchester United | Two or more wins
1996-1997 | Manchester United | Two or more wins
1997-1998 | Arsenal | Two or more wins
1998-1999 | Manchester United | Two or more wins
1999-2000 | Manchester United | Two or more wins
2000-2001 | Manchester United | Two or more wins
2001-2002 | Arsenal | Two or more wins
2002-2003 | Manchester United | Two or more wins
2003-2004 | Arsenal | Two or more wins
2004-2005 | Chelsea | Two or more wins
2005-2006 | Chelsea | Two or more wins
2006-2007 | Manchester United | Two or more wins
2007-2008 | Manchester United | Two or more wins
2008-2009 | Manchester United | Two or more wins
2009-2010 | Chelsea | Two or more wins
2010-2011 | Manchester United | Two or more wins
2011-2012 | Manchester City | Two or more wins
2012-2013 | Manchester United | Two or more wins
2013-2014 | Manchester City | Two or more wins
2014-2015 | Chelsea | Two or more wins
2015-2016 | Leicester City | One win
2016-2017 | | Unknown
(25 rows)
Searched CASE example:
select seasonid, htid, atid, case
when ftscore='0-0' then 'Bore draw'
when ftscore='1-1' then 'Score draw'
when ftscore='2-2' then 'Score draw'
when ftscore='3-3' then 'Score draw'
when ftscore='4-4' then 'Score draw'
when ftscore='5-5' then 'Score draw'
else 'Not a draw'
end
from match
where seasonid=22 and htid=45
order by htid, atid;
seasonid | htid | atid | case
----------+------+------+------------
22 | 45 | 51 | Not a draw
22 | 45 | 52 | Bore draw
22 | 45 | 61 | Not a draw
22 | 45 | 63 | Not a draw
22 | 45 | 65 | Not a draw
22 | 45 | 67 | Not a draw
22 | 45 | 68 | Not a draw
22 | 45 | 69 | Not a draw
22 | 45 | 73 | Not a draw
22 | 45 | 74 | Not a draw
22 | 45 | 75 | Not a draw
22 | 45 | 77 | Not a draw
22 | 45 | 78 | Not a draw
22 | 45 | 86 | Not a draw
22 | 45 | 87 | Not a draw
22 | 45 | 88 | Bore draw
22 | 45 | 89 | Not a draw
22 | 45 | 91 | Not a draw
22 | 45 | 93 | Score draw
(19 rows)
Parent topic:Conditional Expressions