Sunday, June 5, 2022

Only one expression can be specified in the select list when the subquery is not introduced with EXISTS

Msg 116, Level 16, State 1, Line 1
Only one expression can be specified in the select list when the subquery is not introduced with EXISTS.

This error is usually encountered when using a sub-query together with the IN or NOT IN logical operator. The IN logical operator determines whether a specified value matches any value in a subquery or a list.

Select EmployeeID,FirstName,LastName 
from Employee
where EmployeeID IN (Select EmployeeID,FirstName from Employee)

Output:

Msg 116, Level 16, State 1, Line 1
Only one expression can be specified in the select list when the subquery is not introduced with EXISTS.

You can't return two (or multiple) columns in your subquery to do the comparison in the EmployeeID IN (subquery) clause - which column is it supposed to compare EmployeeID to? The subquery must only return the one column needed for the comparison to the column on the other side of the IN. So the query needs to be of the form:

Select EmployeeID,FirstName,LastName 
from Employee
where EmployeeID IN (Select EmployeeID from Employee)

You also want to add sorting so you can select just from the top rows, but you don't need to return the COUNT as a column in order to do your sort; sorting in the ORDER clause is independent of the columns returned by the query.


No comments:

Post a Comment