Case Statements

Estimated reading: 1 minute 16 views

1. What is a CASE statement in SQL?

A CASE statement in SQL is used to perform conditional logic within a query. It allows you to return different values based on specified conditions, similar to an IF-ELSE structure in programming. It can be used in SELECT, UPDATE, DELETE, and INSERT queries to conditionally transform or filter data.

The syntax is:

				
					CASE 
    WHEN condition1 THEN result1
    WHEN condition2 THEN result2
    ELSE result3
END

				
			
  • WHEN condition: Specifies the condition to check.
  • THEN result: The value returned when the condition is true.
  • ELSE result: (Optional) The value returned if none of the conditions are true.

2. How do you use a CASE statement in a SELECT query?

You can use the CASE statement within a SELECT query to apply conditional logic to specific columns.

Example:

				
					SELECT name, salary,
       CASE
           WHEN salary < 50000 THEN 'Low'
           WHEN salary BETWEEN 50000 AND 100000 THEN 'Medium'
           ELSE 'High'
       END AS salary_category
FROM employees;

				
			
  • This query categorizes employees into salary groups based on their salary:
    • ‘Low’ for salaries under 50,000.
    • ‘Medium’ for salaries between 50,000 and 100,000.
    • ‘High’ for salaries over 100,000.
  • The result of the CASE statement is returned as a new column, salary_category.

Leave a Comment

Share this Doc

Case Statements

Or copy link

CONTENTS