Skip to content
Advertisement

MySQL:How to Rewrite a Select element as ‘y’ then using that later in a where statement

So what im trying to do is this but this doesn’t work:

Here is another example:

Advertisement

Answer

You can’t use an aggregate expression (sum(), count(), …) in the where clause of the query. This clause is evaluated before rows are grouped together by the group by clause, so the aggregates are not yet available.

In SQL, that’s the purpose of the having clause:


As for the second query: the alias defined in the select clause is not available in the where clause either (for the same reason as above). You can repeat the expression:

Or you can use a derived table (cte or subquery):

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