MySQL IF

The IF function in MySQL performs conditional logic in your query. It returns one value if a condition is TRUE and another value if it is FALSE.

Examples with Tamil Kings

1. Using IF to Categorize Reign Length

SELECT king_name, IF(reign_years > 30, 'Long Reign', 'Short Reign') AS reign_category FROM tamil_kings_auto_increment;

Code Explanation: This query uses the IF function to categorize kings as having a 'Long Reign' if they ruled for more than 30 years, otherwise 'Short Reign'.

2. Using IF to Handle NULL Values

SELECT king_name, IF(reign_period IS NULL, 'Unknown Period', reign_period) AS period_description FROM tamil_kings_auto_increment;

Code Explanation: This query returns 'Unknown Period' if reign_period is NULL, otherwise it returns the actual reign_period.

Best Practices

  • Use IF to perform conditional checks within your query.
  • Be careful with complex conditions, as they can make queries harder to read and maintain.

Key Takeaways

  • The IF function allows conditional logic in SQL queries.
  • It is useful for categorizing or handling NULL values.