Choose() vs Case statements in SQL Server

Nidhi Gupta
3 min readAug 13, 2021

To understand the working of choose() function and case statements in SQL Server.

Let’s first understand the syntax (how we write choose() function and case statements in SQL Server) then we will check the performance between the two with bulk data.

Consider a table called Emp_Details having columns Id, Name, and DOB(date of birth).

CREATE TABLE Emp_Details

(

Id int,

Name varchar(20),

DOB date

);

Let’s add some data to Emp_Details

INSERT INTO Emp_Details VALUES

(1,’Mark’,’1980–01–11'),(2,’John’,’1981–12–12'),(3,’Amy’,’1979–11–21'),

(4,’Ben’,’1978–05–14'),(5,’Sara’,’1970–03–17'),(6,’David’,’1978–04–05');

Problem Statement:- Write an SQL query to fetch Name, DOB, and MonthName from DOB.

Solution:-

  1. By using CHOOSE() function

SELECT Name, DOB,

CHOOSE(DATEPART(MONTH,DOB),’Jan’,’Feb’,’March’,’April’,’May’,’April’

,’May’,’June’,’July’,’Aug’,’Sep’,’Oct’,’Nov’,’Dec’) as [Month]

FROM Emp_Details;

Result :-CHOOSE()

2. By using CASE statements

SELECT Name, DOB,

CASE DATEPART(MONTH, DOB)

WHEN 1 THEN ‘Jan’

WHEN 2 THEN ‘Feb’

WHEN 3 THEN ‘March’

WHEN 4 THEN ‘April’

WHEN 5 THEN ‘May’

WHEN 6 THEN ‘June’

WHEN 7 THEN ‘July’

WHEN 8 THEN ‘Aug’

WHEN 9 THEN ‘Sep’

WHEN 10 THEN ‘Oct’

WHEN 11 THEN ‘Nov’

WHEN 12 THEN ‘Dec’

END

AS [Month] FROM Emp_Details

Result:- CASE STATEMENT

Now, let us add bulk data to Emp_Details to check which is the more optimized CHOOSE() or Case statements to write queries.

Initial Records in the table:

SELECT COUNT(*) as Total_Count FROM Emp_Details;

SCRIPT FOR BULK DATA INSERTION

BEGIN

DECLARE @Row_Count NVARCHAR(20)

DECLARE @Id INT=1

SET NOCOUNT ON

PRINT(‘Data Insertion In Emp_Details Table’)

WHILE(@Id<=100000)

BEGIN

INSERT INTO Emp_Details

VALUES

(@Id,’Name -’+ CAST(@Id AS NVARCHAR(20)),GETDATE())

SET @ID=@ID+1

END

SET @Row_Count = (SELECT COUNT(*) FROM Emp_Details);

PRINT(‘TOTAL RECORDS INSERTED ‘ + @Row_Count)

END

Records in the table after the above script execution:

SELECT COUNT(*) as Total_Count FROM Emp_Details;

Time taken by Choose() function to fetch 100000 entries

Time taken by Choose() function query

Time taken by Case statements to fetch 100000 entries

Time taken by Case statements query

Do clap, if find useful!🙂

--

--

Nidhi Gupta

Azure Data Engineer 👨‍💻.Heading towards cloud technologies expertise✌️.