How to use a case statement in sql
The CASE
statement in SQL is a way to perform conditional logic. It can be used within SELECT statements, INSERT statements, UPDATE statements, and WHERE clauses. It's similar to the IF-THEN-ELSE
construct found in other programming languages.
Here is an example of a CASE
statement used in a SQL query:
sqlCopy code
SELECT EmployeeID, FirstName, LastName, JobTitle, Salary, -- CASE statement within a SELECT query CASE WHEN Salary >= 70000 THEN 'High' WHEN Salary >= 50000 AND Salary < 70000 THEN 'Medium' ELSE 'Low' END AS SalaryRange FROM Employees;
In this example:
The
CASE
the statement is used to categorize employees based on their salary into 'High', 'Medium', or 'Low' salary ranges.If
Salary
is 70000 or more, theSalaryRange
will be 'High'.If
Salary
is between 50000 and 69999, theSalaryRange
will be 'Medium'.If
Salary
is less than 50000, theSalaryRange
will be 'Low'.The result of the
CASE
statement is returned in a new column calledSalaryRange
.
This is a simple demonstration to show how CASE
can be used to evaluate conditions and return a value based on the result. The CASE
statement is versatile and can be used in various parts of a SQL query.