CASE Statement

The CASE statement allows you to create conditional logic in SQL queries. It works similarly to an IF-THEN-ELSE structure in programming languages.

Example: Using CASE in SELECT

SELECT Name,
       City,
       CASE 
           WHEN Contribution = 'Healthcare' THEN 'Healthcare Activist'
           WHEN Contribution = 'Education' THEN 'Education Reformer'
           ELSE 'General Activist'
       END AS ActivistType
FROM FreedomFighters;

Output:

Returns the name, city, and the activist type based on the contribution.

Do's and Don'ts

Do's

  • Use CASE for conditional transformations in query results.
  • Ensure all conditions are mutually exclusive for clarity.

Don'ts

  • Don't use CASE for operations that can be simplified with built-in functions.
  • Don't leave out the ELSE clause unless default behavior is unnecessary.