Question

Can I have arithmetic operator in SQL having clause? Because from what i know arithmetic operators are only allowed in SELECT and WHERE clause. But the following code make sense to me though, but I know it serves no purpose. Any advice?

 SELECT E.name
 FROM Example E
 GROUP BY E.name
 HAVING COUNT(*) + 2 > 4
Was it helpful?

Solution

Yes, you can use "arithmetic operator" in a HAVING clause.

The expression in the HAVING clause will be evaluated as a boolean.


NOTE: be sure the order of precedence is what you expect, e.g.

( COUNT(*) + 2 ) > 4 

vs

COUNT(*) + ( 2 > 4 )

In your example, the addition isn't really required; the expression could be replace with the logically equivalent:

COUNT(*) > 2

OTHER TIPS

If you want a more complicated arithmetic expression, you can use a subquery:

select
    *
from
(
    select
        cnt = COUNT(*) + 2
        , E.Name
    from
        Example E
    group by
        E.name
) as subQ
where
    subQ.cnt > 4
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top