Introduction
In some cases, using the CASE statement can lead to numerous conditions. You may agree; these multiple conditions will look extensive and lengthy in some situations. Moreover, it can be challenging to maintain because of its complexity.
In this post, we'll explore the SQL CHOOSE function. It helps developers have a better alternative to the CASE statement when simplifying lengthy conditions.
What's CHOOSE Function in SQL Server?
- Introduced in SQL Server 2012
- A function returns a specific value from a list based on its number index.
- It looks like an array, but the index starts from 1.
Syntax
CHOOSE (INDEX, VALUE1, VALUE2, VALUE3, VALUE4...)
Index
This is the element's position we seek in the output. Remember that SQL CHOOSE doesn't use a zero-based index strategy (meaning the first item starts with 1). If the index is not an integer, SQL converts it to an integer; otherwise, it returns NULL.
Values
It is a comma-separated list of any data type. Returns an item based on the index specified in the first(index) parameter.
Example 1. Item index starts at 1
--Let's just say we wanted to list our favorite programming languages
--output: JavaScript
SELECT CHOOSE (1, 'JavaScript','Python', 'C#', 'C++', 'C') as 'Programming Language'
--output: Python
SELECT CHOOSE (2, 'JavaScript','Python', 'C#', 'C++', 'C') as 'Programming Language'
--output: C#
SELECT CHOOSE (3, 'JavaScript','Python', 'C#', 'C++', 'C') as 'Programming Language'
--output: C++
SELECT CHOOSE (4, 'JavaScript','Python', 'C#', 'C++', 'C') as 'Programming Language'
--output: C
SELECT CHOOSE (5, 'JavaScript','Python', 'C#', 'C++', 'C') as 'Programming Language'
Output

Example 2. When CHOOSE Function Returns NULL
--output: NULL
SELECT CHOOSE (0, 'JavaScript','Python', 'C#', 'C++', 'C') as 'Programming Language'
--output: NULL
SELECT CHOOSE (6, 'JavaScript','Python', 'C#', 'C++', 'C') as 'Programming Language'
Output

If we have passed the index outside the value list range, you'll get NULL as the return value.
Example 3. Using Float or Decimal as Index Values
--output: NULL
SELECT CHOOSE (0.10, 'JavaScript','Python', 'C#', 'C++', 'C') as 'Programming Language'
--output: JavaScript
SELECT CHOOSE (1.10, 'JavaScript','Python', 'C#', 'C++', 'C') as 'Programming Language'
--output: Python
SELECT CHOOSE (2.23, 'JavaScript','Python', 'C#', 'C++', 'C') as 'Programming Language'
--output: C#
SELECT CHOOSE (3.9923423, 'JavaScript','Python', 'C#', 'C++', 'C') as 'Programming Language'
--output: C++
SELECT CHOOSE (4.7412122, 'JavaScript','Python', 'C#', 'C++', 'C') as 'Programming Language'
--output: C
SELECT CHOOSE (5, 'JavaScript','Python', 'C#', 'C++', 'C') as 'Programming Language'
--output: NULL
SELECT CHOOSE (6.636, 'JavaScript','Python', 'C#', 'C++', 'C') as 'Programming Language'





Join the conversation! Your thoughts help the community grow.