Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ Nested and Multiple CASE WHEN Conditions | Advanced CASE WHEN Logic
Mastering CASE WHEN in SQL

bookNested and Multiple CASE WHEN Conditions

メニューを表示するにはスワイプしてください

When working with real-world data, you often need to handle complex logic that goes beyond simple single-condition checks. There are scenarios where you must evaluate multiple criteria at once or even build layered decision trees inside your SQL queries. In such cases, using nested or multiple CASE WHEN statements allows you to express advanced logic directly within your SQL, making your queries powerful and adaptable to a wide range of business rules.

123456789101112131415161718
SELECT name, department, years_at_company, CASE WHEN department = 'Engineering' THEN CASE WHEN years_at_company >= 5 THEN 'Eligible for Senior Bonus' ELSE 'Eligible for Standard Bonus' END WHEN department = 'Sales' THEN CASE WHEN years_at_company >= 3 THEN 'Eligible for Sales Bonus' ELSE 'Not Eligible' END ELSE 'Not Eligible' END AS bonus_eligibility FROM employees;
copy

Nesting works by embedding one CASE WHEN statement inside another, allowing you to apply different logic based on an initial condition. In the query above, the outer CASE checks the employee's department. If the department is "Engineering", it uses an inner CASE to decide between a Senior or Standard bonus based on years_at_company. If the department is "Sales", another inner CASE checks if the employee qualifies for a sales bonus. This structure is helpful when your decision-making depends on more than one factor and those factors are related in a hierarchy. You should use nesting when your logic naturally breaks down into main categories with sub-decisions under each category.

12345678910
SELECT name, salary, CASE WHEN salary >= 100000 THEN 'Executive Band' WHEN salary >= 80000 AND salary < 100000 THEN 'Senior Band' WHEN salary >= 60000 OR department = 'Human Resources' THEN 'Mid Band' ELSE 'Entry Band' END AS salary_band FROM employees;
copy
question mark

What is a key reason to use nested CASE WHEN statements?

正しい答えを選んでください

すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 2.  1

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

セクション 2.  1
some-alt