Why do you need to place columns you create yourself (for example select 1 as "number"
) after HAVING
and not WHERE
in MySQL?
And are there any downsides instead of doing WHERE 1
(writing the whole definition instead of a column name)?
Both the statements will be having same performance as SQL Server is smart enough to parse both the same statements into a similar plan. So, it does not matter if you use WHERE or HAVING in your query.
A HAVING clause is like a WHERE clause, but applies only to groups as a whole (that is, to the rows in the result set representing groups), whereas the WHERE clause applies to individual rows. A query can contain both a WHERE clause and a HAVING clause.
The difference between the having and where clause in SQL is that the where clause cannot be used with aggregates, but the having clause can. The where clause works on row's data, not on aggregated data. Let us consider below table 'Marks'. This would select data row by row basis.
Well, the main distinction between the two clauses is that HAVING can be applied for subsets of aggregated groups, while in the WHERE block, this is forbidden. In simpler words, after HAVING, we can have a condition with an aggregate function, while WHERE cannot use aggregate functions within its conditions.
Why is it that you need to place columns you create yourself (for example "select 1 as number") after HAVING and not WHERE in MySQL?
WHERE
is applied before GROUP BY
, HAVING
is applied after (and can filter on aggregates).
In general, you can reference aliases in neither of these clauses, but MySQL
allows referencing SELECT
level aliases in GROUP BY
, ORDER BY
and HAVING
.
And are there any downsides instead of doing "WHERE 1" (writing the whole definition instead of a column name)
If your calculated expression does not contain any aggregates, putting it into the WHERE
clause will most probably be more efficient.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With