📜  mysql switch case - SQL (1)

📅  最后修改于: 2023-12-03 15:33:02.074000             🧑  作者: Mango

MySQL Switch Case - SQL

MySQL Switch Case is a powerful feature of SQL which allows you to perform conditional operations based on the value of a specified expression. It is a way to simplify complex if-else conditions and make your SQL code more efficient and readable.

Syntax

The switch case statement in MySQL has the following syntax :

CASE value
    WHEN cond1 THEN result1
    WHEN cond2 THEN result2
    ...
    ELSE result
END;

Here, value is the expression you want to compare against the conditions specified in the WHEN clause. cond1, cond2 etc. are the conditions to be checked against the value. If a condition is met, result1, result2 etc. are returned respectively. The ELSE clause specifies the result to be returned if none of the conditions are met.

Example

Let's take an example to understand how switch case works:

Suppose you have a table called students with columns id, name, age and marks.

CREATE TABLE students(
  id int primary key,
  name varchar(50),
  age int,
  marks int
);

Now, suppose you want to perform the following operations -

  • If the student's age is less than 18, assign 'Minor' as their category.
  • If the student's age is greater than or equal to 18, but less than 25, assign 'Young' as their category.
  • If the student's age is greater than or equal to 25, but less than 40, assign 'Adult' as their category.
  • If the student's age is greater than or equal to 40, assign 'Senior' as their category.

You can achieve this using switch case in the following way:

SELECT name,
       age,
       marks,
       CASE
           WHEN age < 18 THEN 'Minor'
           WHEN age >= 18 AND age < 25 THEN 'Young'
           WHEN age >= 25 AND age < 40 THEN 'Adult'
           ELSE 'Senior'
       END AS category
FROM students;

The above SQL code will return a table with names, age, marks and their respective categories as shown below -

|name|age|marks|category| |----|---|-----|--------| |John|16 |86 |Minor | |Mary|20 |78 |Young | |Tim |30 |92 |Adult |

In this example, MySQL switch case statement has been used to assign a category to students based on their age.

Conclusion

MySQL switch case is a powerful way to simplify complex if-else conditions and make your SQL code more efficient and readable. With this feature, you can perform conditional operations based on the value of a specified expression. It is an essential tool for any developer who works with databases and wants to optimize their SQL queries.