MySQL CASE

The CASE statement in MySQL is used to handle conditional logic. It allows you to create conditions in a query and return different results based on those conditions.

Examples with Tamil Kings

1. Simple CASE Statement

SELECT king_name,
CASE reign_period
    WHEN '985–1014 CE' THEN 'Golden Era'
    WHEN '1014–1044 CE' THEN 'Expansion Era'
    ELSE 'Unknown Era'
END AS era_description
FROM tamil_kings_auto_increment;

Code Explanation: This query uses a CASE statement to categorize the reign_period into descriptive eras.

2. Searched CASE Statement

SELECT king_name,
CASE
    WHEN reign_years > 30 THEN 'Long Reign'
    WHEN reign_years BETWEEN 10 AND 30 THEN 'Moderate Reign'
    ELSE 'Short Reign'
END AS reign_duration
FROM tamil_kings_auto_increment;

Code Explanation: This query uses a CASE statement to categorize kings based on the number of reign_years.

Best Practices

  • Use CASE for conditional logic in SELECT queries.
  • Ensure all possible cases are covered, and use ELSE to handle unexpected values.

Key Takeaways

  • The CASE statement provides conditional logic in SQL queries.
  • It can be used to create more readable and flexible queries.