r/SQL • • Oct 07 '26

MySQL Difference between "having" and "qualify"

I tried to use both methods in order to save some coding but still didnt get the exact difference on using having and qualify as a filter in the end of a query. Can someone help me to understand the difference and when is recommended to use each?

23 Upvotes

11 comments sorted by

View all comments

1

u/konwiddak Oct 07 '26

WHERE happens while retrieving data - the data is filtered out as early as possible, often by the index or at table scan and never even loaded into memory. The data never becomes part of calculations, aggregates or window functions.

HAVING and QUALIFY happen after all the data has been retrieved and built into a dataset. Calculations/aggregates/window functions happen against the full dataset. Then these two functions apply before returning the dataset to the user (or out of the subquery.)

HAVING can be used on aggregates (e.g SUM(column) > 3)

QUALIFY can be used on normal columns like a where, or on window functions. In effect with simple filters the output looks the same as a WHERE clause - but more work has to be done by the database.

You can't use WHERE on aggregates or window functions, because filtering the data changes the result, which changes the aggregate/window function which changes the filtered result.