I'm going through a DataCamp course on SQL. This course examines the European soccer database.
Part of the course discusses using CASE as a filter, so that you are not left with a chunk of NULL values. The following code is offered to filter specifically Chelsea home and road victories:
SELECT date, season,
CASE WHEN hometeam_id = 8455 AND home_goal > away_goal
THEN 'Chelsea home win!'
WHEN awayteam_id = 8455 AND home_goal < away_goal
THEN 'Chelsea away win!' END AS outcome
FROM match
WHERE CASE WHEN hometeam_id = 8455 AND home_goal > away_goal
THEN 'Chelsea home win!'
WHEN awayteam_id = 8455 AND home_goal < away_goal
THEN 'Chelsea away win!' END IS NOT NULL;
Looking at this code, there seems to be some superfluity. The CASE in the filter, for example, defines categories a second time, even though it was done during the SELECT clause. It seems to me that it would be more advantageous to simply use AND and OR in the filter:
SELECT date, season,
CASE WHEN hometeam_id = 8455 AND home_goal > away_goal
THEN 'Chelsea home win!'
WHEN awayteam_id = 8455 AND home_goal < away_goal
THEN 'Chelsea away win!' END AS outcome
FROM match
WHERE (hometeam_id = 8455 AND home_goal > away_goal)
OR (awayteam_id = 8455 AND home_goal < away_goal);
So a couple of questions.
- Is there a particular reason for using the
CASEclause like this? Or is the DataCamp course just using theCASEin a filter in a teachable way, and this partcular case is not necessarily a practical use? - What does assigning categories in the filtering
CASEclause do, as seen in the first query? - If we are filtering on the
CASEclause, then why not simply end withWHERE outcome IS NOT NULL?
Again, I understand if it's entirely just to teach a principle--the first question still stands, in that case--but assuming there's a deeper, more complex reason behind all this verbosity, what is it?