Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WHERE vs HAVING

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)?

like image 945
baloo Avatar asked Oct 06 '22 09:10

baloo


People also ask

Which is better WHERE or HAVING?

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.

What is the difference between WHERE & HAVING clause?

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.

Is HAVING better than WHERE SQL?

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.

Can we use HAVING instead of WHERE?

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.


1 Answers

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.

like image 337
Quassnoi Avatar answered Oct 12 '22 20:10

Quassnoi