BASED IN Antioch, TENNESSEE, CNM TECH IS A BLOG BY CHARLES MCDOWELL. HIS POSTS EXPLORE his studies on computer technology through photos, cool quotes, and study guides.

How to use a case statement in sql

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, the SalaryRange will be 'High'.

  • If Salary is between 50000 and 69999, the SalaryRange will be 'Medium'.

  • If Salary is less than 50000, the SalaryRange will be 'Low'.

  • The result of the CASE statement is returned in a new column called SalaryRange.

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.

How to do a while loop and if statements in sql

How to do a while loop and if statements in sql