How is HAVING different from WHERE when filtering grouped results?
Quick answer
Use WHERE to remove individual rows before the database forms groups. Use HAVING to keep or discard groups after grouping, often by testing an aggregate such as SUM. For example, WHERE amount > 0 excludes nonpositive transactions before totals are calculated, while HAVING SUM(amount) >= 100 keeps only groups whose resulting total is at least 100. [S1]
The question, the details, the next step.
A practical checklist
Write down which individual rows should contribute to the calculation.
Put row-level filters in WHERE when they should be applied before grouping.
Choose the grouping column or columns in GROUP BY.
Put conditions on group summaries, such as SUM(amount), in HAVING.
Test the query with a few hand-calculated rows, including a row that WHERE excludes and a group that HAVING rejects.
A few more useful answers
Does WHERE filter groups?
WHERE filters input rows before groups are formed. To keep or discard completed groups based on an aggregate, use HAVING. [S1]
Can a query use both WHERE and HAVING?
Yes. Use WHERE to select contributing rows and HAVING to filter the resulting groups, as in the sales example. [S1]
Does HAVING always need an aggregate?
The example and cited SQLite guidance show HAVING evaluated for each group, with aggregates evaluated across that group. They do not establish rules for every database or every kind of HAVING expression, so check the documentation for your database when using other forms. [S1]
Sources
References used for this guide.
- [S1] SQLite SELECT: WHERE, GROUP BY, and HAVING processing sqlite.org · Checked
