CASE WHEN

The CASE WHEN statement is very useful and is similar to an IF statement in SQL. It will create a new column with data, and in each row, there will be different data depending on what the CASE WHEN statement outlines:

SELECT *, CASE WHEN 2023 estimate > 1000000 THEN ‘Above 1 mn‘ ELSE ‘Less THAN 1 mn‘ END as ‘Population Category‘

FROM database_table

  • The general format of the CASE WHEN is

    • CASE WHEN column name comparison THEN ‘label for this category‘

      ELSE ‘label for any category that did not fall into the above categories‘ END

  • So the first CASE WHEN comparison compares the 2023 estimate’s column to see if the population is above 1,000,000 people, and if it is, then it will assign that new row as ‘Above 1 mn‘. The ELSE statement accounts for everything else, so if the population is under 1,000,000 like Fort Worth, then it will assign that row as ‘Less Than 1 mn‘