Skip to content
Advertisement

Select clause result as comparison expression

In Sql queries can I use the result of a select clause using aggregate functions as an expression for a comparison?

For example:

HAVING COUNT(a) = SELECT COUNT(b) FROM c WHERE b=1

Advertisement

Answer

Yes, you can do this. You just need parentheses as you would with any subquery:

HAVING COUNT(a) = (SELECT COUNT(b) FROM c WHERE b=1)

Note that count(b) is not necessary when you know that b is not NULL. There is no need to check for NULL values, so:

HAVING COUNT(a) = (SELECT COUNT(*) FROM c WHERE b = 1)
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement