How to write sql code with CASE
- User
How to write sql code with CASE
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
How to write sql code with CASE
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
The CASE statement in SQL is used to add conditional logic to your queries. It allows you to evaluate a list of conditions and return a value when the first condition is met. If no conditions are met, it can return a default value.
Here's the basic syntax for the CASE statement:
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
...
ELSE default_result
END
CASE StatementSuppose you have a table named employees with columns id, name, and salary. You want to categorize employees based on their salary.
SELECT
id,
name,
salary,
CASE
WHEN salary < 30000 THEN 'Low'
WHEN salary BETWEEN 30000 AND 70000 THEN 'Medium'
ELSE 'High'
END AS salary_category
FROM
employees;
CASE Statement with Aggregate FunctionsYou can also use CASE statements within aggregate functions. For example, you might want to count the number of employees in each salary category.
SELECT
CASE
WHEN salary < 30000 THEN 'Low'
WHEN salary BETWEEN 30000 AND 70000 THEN 'Medium'
ELSE 'High'
END AS salary_category,
COUNT(*) AS number_of_employees
FROM
employees
GROUP BY
CASE
WHEN salary < 30000 THEN 'Low'
WHEN salary BETWEEN 30000 AND 70000 THEN 'Medium'
ELSE 'High'
END;
CASE Statement in WHERE ClauseYou can use CASE statements in the WHERE clause to filter rows based on conditions.
SELECT
id,
name,
salary
FROM
employees
WHERE
CASE
WHEN salary < 30000 THEN 'Low'
WHEN salary BETWEEN 30000 AND 70000 THEN 'Medium'
ELSE 'High'
END = 'High';
CASE Statement with Multiple ConditionsYou can have multiple conditions within a CASE statement.
SELECT
id,
name,
salary,
CASE
WHEN salary < 30000 AND department = 'Sales' THEN 'Low Sales'
WHEN salary BETWEEN 30000 AND 70000 AND department = 'Engineering' THEN 'Medium Engineering'
ELSE 'Other'
END AS category
FROM
employees;
CASE Statement with SubqueriesYou can also use CASE statements with subqueries.
SELECT
id,
name,
salary,
CASE
WHEN (SELECT COUNT(*) FROM projects WHERE projects.employee_id = employees.id) > 5 THEN 'High Activity'
ELSE 'Low Activity'
END AS activity_level
FROM
employees;
CASE StatementsCASE statements simple and readable. Complex logic can be hard to maintain.CASE statements in the WHERE clause or with subqueries.CASE results to make your queries easier to understand.By using CASE statements effectively, you can add powerful conditional logic to your SQL queries, making them more flexible and capable of handling a wide range of scenarios.