CASE (Transact-SQL) - SQL Server (2024)

  • Article

Applies to: CASE (Transact-SQL) - SQL Server (1) SQL Server CASE (Transact-SQL) - SQL Server (2) Azure SQL Database CASE (Transact-SQL) - SQL Server (3) Azure SQL Managed Instance CASE (Transact-SQL) - SQL Server (4) Azure Synapse Analytics CASE (Transact-SQL) - SQL Server (5) Analytics Platform System (PDW) CASE (Transact-SQL) - SQL Server (6) SQL analytics endpoint in Microsoft Fabric CASE (Transact-SQL) - SQL Server (7) Warehouse in Microsoft Fabric

Evaluates a list of conditions and returns one of multiple possible result expressions.

The CASE expression has two formats:

  • The simple CASE expression compares an expression to a set of simple expressions to determine the result.

  • The searched CASE expression evaluates a set of Boolean expressions to determine the result.

Both formats support an optional ELSE argument.

CASE can be used in any statement or clause that allows a valid expression. For example, you can use CASE in statements such as SELECT, UPDATE, DELETE and SET, and in clauses such as <select_list>, IN, WHERE, ORDER BY, and HAVING.

CASE (Transact-SQL) - SQL Server (8) Transact-SQL syntax conventions

Syntax

Syntax for SQL Server, Azure SQL Database and Azure Synapse Analytics.

-- Simple CASE expression:CASE input_expression WHEN when_expression THEN result_expression [ ...n ] [ ELSE else_result_expression ]END-- Searched CASE expression:CASE WHEN Boolean_expression THEN result_expression [ ...n ] [ ELSE else_result_expression ]END

Syntax for Parallel Data Warehouse.

CASE WHEN when_expression THEN result_expression [ ...n ] [ ELSE else_result_expression ]END

Arguments

input_expression

The expression evaluated when the simple CASE format is used. input_expression is any valid expression.

WHEN when_expression

A simple expression to which input_expression is compared when the simple CASE format is used. when_expression is any valid expression. The data types of input_expression and each when_expression must be the same or must be an implicit conversion.

THEN result_expression

The expression returned when input_expression equals when_expression evaluates to TRUE, or Boolean_expression evaluates to TRUE. result expression is any valid expression.

ELSE else_result_expression

The expression returned if no comparison operation evaluates to TRUE. If this argument is omitted and no comparison operation evaluates to TRUE, CASE returns NULL. else_result_expression is any valid expression. The data types of else_result_expression and any result_expression must be the same or must be an implicit conversion.

WHEN Boolean_expression

The Boolean expression evaluated when using the searched CASE format. Boolean_expression is any valid Boolean expression.

Return types

Returns the highest precedence type from the set of types in result_expressions and the optional else_result_expression. For more information, see Data Type Precedence (Transact-SQL).

Return values

Simple CASE expression:

The simple CASE expression operates by comparing the first expression to the expression in each WHEN clause for equivalency. If these expressions are equivalent, the expression in the THEN clause will be returned.

  • Allows only an equality check.

  • In the order specified, evaluates input_expression = when_expression for each WHEN clause.

  • Returns the result_expression of the first input_expression = when_expression that evaluates to TRUE.

  • If no input_expression = when_expression evaluates to TRUE, the SQL Server Database Engine returns the else_result_expression if an ELSE clause is specified, or a NULL value if no ELSE clause is specified.

Searched CASE expression:

  • Evaluates, in the order specified, Boolean_expression for each WHEN clause.

  • Returns result_expression of the first Boolean_expression that evaluates to TRUE.

  • If no Boolean_expression evaluates to TRUE, the Database Engine returns the else_result_expression if an ELSE clause is specified, or a NULL value if no ELSE clause is specified.

Remarks

SQL Server allows for only 10 levels of nesting in CASE expressions.

The CASE expression can't be used to control the flow of execution of Transact-SQL statements, statement blocks, user-defined functions, and stored procedures. For a list of control-of-flow methods, see Control-of-Flow Language (Transact-SQL).

The CASE expression evaluates its conditions sequentially and stops with the first condition whose condition is satisfied. In some situations, an expression is evaluated before a CASE expression receives the results of the expression as its input. Errors in evaluating these expressions are possible. Aggregate expressions that appear in WHEN arguments to a CASE expression are evaluated first, then provided to the CASE expression. For example, the following query produces a divide by zero error when producing the value of the MAX aggregate. This occurs prior to evaluating the CASE expression.

WITH Data (value)AS ( SELECT 0 UNION ALL SELECT 1 )SELECT CASE WHEN MIN(value) <= 0 THEN 0 WHEN MAX(1 / value) >= 100 THEN 1 ENDFROM Data;GO

You should only depend on order of evaluation of the WHEN conditions for scalar expressions (including non-correlated subqueries that return scalars), not for aggregate expressions.

You must also ensure that at least one of the expressions in the THEN or ELSE clauses isn't the NULL constant. While NULL can be returned from multiple result expressions, not all of these can explicitly be the NULL constant. If all result expressions use the NULL constant, error 8133 is returned.

Examples

A. Use a SELECT statement with a simple CASE expression

Within a SELECT statement, a simple CASE expression allows for only an equality check; no other comparisons are made. The following example uses the CASE expression to change the display of product line categories to make them more understandable.

USE AdventureWorks2022;GOSELECT ProductNumber, Category = CASE ProductLine WHEN 'R' THEN 'Road' WHEN 'M' THEN 'Mountain' WHEN 'T' THEN 'Touring' WHEN 'S' THEN 'Other sale items' ELSE 'Not for sale' END, NameFROM Production.ProductORDER BY ProductNumber;GO

B. Use a SELECT statement with a searched CASE expression

Within a SELECT statement, the searched CASE expression allows for values to be replaced in the result set based on comparison values. The following example displays the list price as a text comment based on the price range for a product.

USE AdventureWorks2022;GOSELECT ProductNumber, Name, "Price Range" = CASE WHEN ListPrice = 0 THEN 'Mfg item - not for resale' WHEN ListPrice < 50 THEN 'Under $50' WHEN ListPrice >= 50 AND ListPrice < 250 THEN 'Under $250' WHEN ListPrice >= 250 AND ListPrice < 1000 THEN 'Under $1000' ELSE 'Over $1000' ENDFROM Production.ProductORDER BY ProductNumber;GO

C. Use CASE in an ORDER BY clause

The following examples use the CASE expression in an ORDER BY clause to determine the sort order of the rows based on a given column value. In the first example, the value in the SalariedFlag column of the HumanResources.Employee table is evaluated. Employees that have the SalariedFlag set to 1 are returned in order by the BusinessEntityID in descending order. Employees that have the SalariedFlag set to 0 are returned in order by the BusinessEntityID in ascending order. In the second example, the result set is ordered by the column TerritoryName when the column CountryRegionName is equal to 'United States' and by CountryRegionName for all other rows.

SELECT BusinessEntityID, SalariedFlagFROM HumanResources.EmployeeORDER BY CASE SalariedFlag WHEN 1 THEN BusinessEntityID END DESC, CASE WHEN SalariedFlag = 0 THEN BusinessEntityID END;GO
SELECT BusinessEntityID, LastName, TerritoryName, CountryRegionNameFROM Sales.vSalesPersonWHERE TerritoryName IS NOT NULLORDER BY CASE CountryRegionName WHEN 'United States' THEN TerritoryName ELSE CountryRegionName END;GO

D. Use CASE in an UPDATE statement

The following example uses the CASE expression in an UPDATE statement to determine the value that is set for the column VacationHours for employees with SalariedFlag set to 0. When subtracting 10 hours from VacationHours results in a negative value, VacationHours is increased by 40 hours; otherwise, VacationHours is increased by 20 hours. The OUTPUT clause is used to display the before and after vacation values.

USE AdventureWorks2022;GOUPDATE HumanResources.EmployeeSET VacationHours = ( CASE WHEN ((VacationHours - 10.00) < 0) THEN VacationHours + 40 ELSE (VacationHours + 20.00) END )OUTPUT Deleted.BusinessEntityID, Deleted.VacationHours AS BeforeValue, Inserted.VacationHours AS AfterValueWHERE SalariedFlag = 0;GO

E. Use CASE in a SET statement

The following example uses the CASE expression in a SET statement in the table-valued function dbo.GetContactInfo. In the AdventureWorks2022 database, all data related to people is stored in the Person.Person table. For example, the person may be an employee, vendor representative, or a customer. The function returns the first and last name of a given BusinessEntityID and the contact type for that person. The CASE expression in the SET statement determines the value to display for the column ContactType based on the existence of the BusinessEntityID column in the Employee, Vendor, or Customer tables.

USE AdventureWorks2022;GOCREATE FUNCTION dbo.GetContactInformation (@BusinessEntityID INT)RETURNS @retContactInformation TABLE ( BusinessEntityID INT NOT NULL, FirstName NVARCHAR(50) NULL, LastName NVARCHAR(50) NULL, ContactType NVARCHAR(50) NULL, PRIMARY KEY CLUSTERED (BusinessEntityID ASC) )AS-- Returns the first name, last name and contact type for the specified contact.BEGIN DECLARE @FirstName NVARCHAR(50), @LastName NVARCHAR(50), @ContactType NVARCHAR(50); -- Get common contact information SELECT @BusinessEntityID = BusinessEntityID, @FirstName = FirstName, @LastName = LastName FROM Person.Person WHERE BusinessEntityID = @BusinessEntityID; SET @ContactType = CASE -- Check for employee WHEN EXISTS ( SELECT * FROM HumanResources.Employee AS e WHERE e.BusinessEntityID = @BusinessEntityID ) THEN 'Employee' -- Check for vendor WHEN EXISTS ( SELECT * FROM Person.BusinessEntityContact AS bec WHERE bec.BusinessEntityID = @BusinessEntityID ) THEN 'Vendor' -- Check for store WHEN EXISTS ( SELECT * FROM Purchasing.Vendor AS v WHERE v.BusinessEntityID = @BusinessEntityID ) THEN 'Store Contact' -- Check for individual consumer WHEN EXISTS ( SELECT * FROM Sales.Customer AS c WHERE c.PersonID = @BusinessEntityID ) THEN 'Consumer' END; -- Return the information to the caller IF @BusinessEntityID IS NOT NULL BEGIN INSERT @retContactInformation SELECT @BusinessEntityID, @FirstName, @LastName, @ContactType; END; RETURN;END;GOSELECT BusinessEntityID, FirstName, LastName, ContactTypeFROM dbo.GetContactInformation(2200);GOSELECT BusinessEntityID, FirstName, LastName, ContactTypeFROM dbo.GetContactInformation(5);GO

F. Use CASE in a HAVING clause

The following example uses the CASE expression in a HAVING clause to restrict the rows returned by the SELECT statement. The statement returns the hourly rate for each job title in the HumanResources.Employee table. The HAVING clause restricts the titles to those that are held by salaried employees with a maximum pay rate greater than 40 dollars, or non-salaried employees with a maximum pay rate greater than 15 dollars.

USE AdventureWorks2022;GOSELECT JobTitle, MAX(ph1.Rate) AS MaximumRateFROM HumanResources.Employee AS eINNER JOIN HumanResources.EmployeePayHistory AS ph1 ON e.BusinessEntityID = ph1.BusinessEntityIDGROUP BY JobTitleHAVING ( MAX(CASE WHEN SalariedFlag = 1 THEN ph1.Rate ELSE NULL END) > 40.00 OR MAX(CASE WHEN SalariedFlag = 0 THEN ph1.Rate ELSE NULL END) > 15.00 )ORDER BY MaximumRate DESC;GO

Examples: Azure Synapse Analytics and Analytics Platform System (PDW)

G. Use a SELECT statement with a CASE expression

Within a SELECT statement, the CASE expression allows for values to be replaced in the result set based on comparison values. The following example uses the CASE expression to change the display of product line categories to make them more understandable. When a value doesn't exist, the text "Not for sale' is displayed.

-- Uses AdventureWorksSELECT ProductAlternateKey, Category = CASE ProductLine WHEN 'R' THEN 'Road' WHEN 'M' THEN 'Mountain' WHEN 'T' THEN 'Touring' WHEN 'S' THEN 'Other sale items' ELSE 'Not for sale' END, EnglishProductNameFROM dbo.DimProductORDER BY ProductKey;GO

H. Use CASE in an UPDATE statement

The following example uses the CASE expression in an UPDATE statement to determine the value that is set for the column VacationHours for employees with SalariedFlag set to 0. When subtracting 10 hours from VacationHours results in a negative value, VacationHours is increased by 40 hours; otherwise, VacationHours is increased by 20 hours.

-- Uses AdventureWorksUPDATE dbo.DimEmployeeSET VacationHours = ( CASE WHEN ((VacationHours - 10.00) < 0) THEN VacationHours + 40 ELSE (VacationHours + 20.00) END )WHERE SalariedFlag = 0;GO

See also

  • Expressions (Transact-SQL)
  • SELECT (Transact-SQL)
  • COALESCE (Transact-SQL)
  • IIF (Transact-SQL)
  • CHOOSE (Transact-SQL)
CASE (Transact-SQL) - SQL Server (2024)
Top Articles
CBS - Administrative
How much do sessions cost?
Renfield Showtimes Near Paragon Theaters - Coral Square
Fbsm St Louis
Abigail Letts O'brien Obituary
Governor Brown Signs Legislation Supporting California Legislative Women's Caucus Priorities
Shoplyfter Dressed For The Occasion
Stranded Alien Dawn Cave Dweller
G122 Pink Pill
Craigslist Hinckley Mn
Craigslist Free Stuff North Jersey
Guilford County Mugshots Zone
Succubus - Female Demon in Medieval Legend | Mythology.net
Runic Ward Chest Vault
184€ Flug Frankfurt am Main - Lahore - Günstige Flüge von Frankfurt am Main nach Lahore - KAYAK
oremus Bible Browser
Pokemon Fire Red Cheats
My Unt Hr
Printable Coupon $3 Off Pull-Ups
UNITE 7SECONDS Condition Leave in Detangler 60ml GWP 60 ml
Csusm Verify My Fafsa
Guardians Of The Galaxy Holiday Special Putlocker
Nacitiprepaid
Uhaul Used Trailer Sales
Autozone Open Am
Electric Toothbrush Feature Crossword
Loopnet Properties For Sale
Locate Td Bank Near Me
Play It Again Sports Knoxville Photos
Jesus Revolution Showtimes Near Amc Classic Findlay 12
Craigslist Red Wing Mn
Dollar Storw Near Me
Обзор открытых наушников Sanag Z66 pro с высокой автономностью
Harris Teeter Path
Ups Drop Off Near By
Woo Pig Softball Tournament 2023
Body Rubs Pittsburgh
South Bend Weather Underground
Huntington Bank Review 2024 | Bankrate
Learn4Good Job Posting
Lucki White House Lyrics
World of Warcraft Bringing Back Old Anniversary Rewards for the First Time in 15 Years
Full Cast Of Red
Excel Module 4 Sam End Of Module Project 2
Xnx Xnx Honeywell Analytics 40
Newcomer Funeral Home Beavercreek Obituaries
Bobs Kart Forum
Lifesafer San Jose
676 Fl Oz To Gallons
Mannat Indian Grocers
Latest Posts
Article information

Author: Nicola Considine CPA

Last Updated:

Views: 5724

Rating: 4.9 / 5 (49 voted)

Reviews: 80% of readers found this page helpful

Author information

Name: Nicola Considine CPA

Birthday: 1993-02-26

Address: 3809 Clinton Inlet, East Aleisha, UT 46318-2392

Phone: +2681424145499

Job: Government Technician

Hobby: Calligraphy, Lego building, Worldbuilding, Shooting, Bird watching, Shopping, Cooking

Introduction: My name is Nicola Considine CPA, I am a determined, witty, powerful, brainy, open, smiling, proud person who loves writing and wants to share my knowledge and understanding with you.