Skip to content
Advertisement

Return only distinct values from multiple SQL correlated sub-queries

This query partially completes. It returns 16 of 1,135 rows. The error message below indicates duplicates in the sub-queries.

I have tried inserting DISTINCT and IN syntax to no avail. Any help would be greatly appreciated.

Msg 512, Level 16, State 1, Line 1 Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= ,>, >= or when the subquery is used as an expression.

Advertisement

Answer

This error message doesn’t indicate duplicates on the correlate subqueries, but multiple values. So it raises an error because the engine can’t determine which of those values is the ones that should be returned.

You can add a TOP 1 on the subqueries to tell the engine that the first value of each subquery is the one to be returned.

But this is not recommended, because you shouldn’t return a random value like that, you should check which subquery unexpectedly returns more than one value, and determine which is the correct of those multiple values, modifying that subquery so it returns that one (using an ORDER BY, for example).

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement