Introduction
Nested CASE expressions help you make decisions inside other decisions in your data queries. This lets you check multiple conditions step by step.
CASE WHEN condition1 THEN CASE WHEN condition2 THEN result2 ELSE result3 END ELSE result1 END
SELECT CASE WHEN score >= 90 THEN 'A' WHEN score >= 80 THEN CASE WHEN score >= 85 THEN 'B+' ELSE 'B' END ELSE 'C' END AS grade FROM students;
SELECT product, CASE WHEN category = 'Fruit' THEN CASE WHEN price < 1 THEN 'Cheap Fruit' ELSE 'Expensive Fruit' END ELSE 'Other' END AS price_label FROM products;
WITH sales AS ( SELECT 'North' AS region, 120 AS amount UNION ALL SELECT 'North', 80 UNION ALL SELECT 'South', 50 UNION ALL SELECT 'South', 200 ) SELECT region, amount, CASE WHEN region = 'North' THEN CASE WHEN amount > 100 THEN 'High North Sale' ELSE 'Low North Sale' END WHEN region = 'South' THEN CASE WHEN amount > 100 THEN 'High South Sale' ELSE 'Low South Sale' END ELSE 'Other Region' END AS sale_category FROM sales;
nested CASE expressions in SQL?Employees with column Salary, what will this query return?SELECT Salary, CASE WHEN Salary > 70000 THEN CASE WHEN Salary > 90000 THEN 'High' ELSE 'Medium' END ELSE 'Low' END AS SalaryLevel FROM Employees;
SELECT CASE WHEN score > 80 THEN CASE score > 90 THEN 'Excellent' ELSE 'Good' END ELSE 'Average' END AS Grade FROM Results;
Price and Stock using nested CASE. If Price > 100 and Stock > 50, label 'Premium-Available'. If Price > 100 and Stock ≤ 50, label 'Premium-Limited'. Otherwise, label 'Standard'. Which SQL snippet correctly implements this?Pass the test and this pattern moves unknown