SQL Server Tutorial SQL Server Advanced SQL Server Database SQL Server References

SQL Server CHOOSE() Function



The SQL Server (Transact-SQL) CHOOSE() function returns the Nth element of the list of items: val1 if N = 1, val2 if N = 2, and so on. It returns NULL if N is less than 1 or greater than the number of items specified as arguments.

Syntax

CHOOSE(N, val1, val2, val3,...)

Parameters

N Required. Specify the index number.
val1, val2, val3,... Required. Specify the list of items.

Return Value

Returns the Nth element of the list of items.

Example 1:

The example below shows the usage of CHOOSE() function.

SELECT CHOOSE(1, 'Learning', 'SQL Server', 'is', 'fun');
Result: 'Learning'

SELECT CHOOSE(2, 'Learning', 'SQL Server', 'is', 'fun');
Result: 'SQL Server'

SELECT CHOOSE(5, 'Learning', 'SQL Server', 'is', 'fun');
Result: NULL

SELECT CHOOSE(0, 'Learning', 'SQL Server', 'is', 'fun');
Result: NULL

SELECT CHOOSE(4, 'Learning', 'SQL Server', 'is', 'fun');
Result: 'fun'

SELECT CHOOSE(3, 10, 20, 30, '40');
Result: 30

Example 2:

Consider a database table called EmployeeLogin with the following records:

EmpIDNameDateLoginTime
1John2019-10-2509:20:38
2Marry2019-10-2509:21:05
3Jo2019-10-2509:24:35
4Kim2019-10-2509:25:24
5Ramesh2019-10-2509:27:16

The following query can be used to get the 2nd element from list of items specified by column records:

SELECT *, 
CHOOSE(2, Name, Date, LoginTime) AS CHOOSE_Value
FROM EmployeeLogin;

This will produce a result similar to:

EmpIDNameDateLoginTimeCHOOSE_Value
1John2019-10-2509:20:382019-10-25
2Marry2019-10-2509:21:052019-10-25
3Jo2019-10-2509:24:352019-10-25
4Kim2019-10-2509:25:242019-10-25
5Ramesh2019-10-2509:27:162019-10-25
6Suresh2019-10-2509:28:192019-10-25

❮ SQL Server Functions