Combining WHERE and HAVING Across Data Levels and Why HAVING Can Mask Filtering Errors
WHERE filters individual rows before grouping while HAVING filters aggregated groups after grouping. When NULL values propagate through aggregates into HAVING conditions, entire groups can be silently dropped, hiding data quality issues rather than surfacing them as exceptions.
On this page
The short answer
The fundamental distinction between WHERE and HAVING is the level of data they operate on. WHERE evaluates predicates against individual rows before any grouping occurs, so it can only reference non-aggregated columns. HAVING evaluates predicates against groups after aggregation, so it can reference aggregate functions like AVG, SUM, and COUNT. This boundary means that a row excluded by WHERE never contributes to any group, while a group excluded by HAVING was fully formed before being filtered out. The danger arises from SQL's three-valued logic. When a comparison involving NULL returns UNKNOWN, the row or group is silently excluded. In WHERE, this means rows with NULL values in the filter column disappear before grouping. In HAVING, if an aggregate over a group evaluates to NULL (for example, AVG over a set of all-NULL values), the comparison NULL > threshold yields UNKNOWN, and the entire group vanishes without any error or warning. This masks the fact that the group had no valid data, making it indistinguishable from a group that legitimately failed the threshold. To combine them correctly, use WHERE to eliminate rows that should never participate in aggregation, and use HAVING to express conditions that genuinely depend on aggregated results. Always add explicit IS NULL or IS NOT NULL checks where NULL presence is meaningful, and consider using COALESCE or NVL to convert NULL aggregates into sentinel values that can be distinguished from valid results.
Execution Order and Data Scope
The SQL processing pipeline applies WHERE before GROUP BY and HAVING after GROUP BY. This ordering defines a hard boundary: WHERE operates on individual rows and can only reference columns that exist in the source table, while HAVING operates on groups and can reference aggregate expressions. A row that fails a WHERE predicate never enters any group, so its absence cannot be detected by HAVING. Conversely, a group that fails a HAVING predicate was fully formed with all its member rows before being excluded from the result set.
This distinction matters because it determines what information is available at each filtering stage. If you need to exclude rows based on a non-aggregated condition, it must go in WHERE. If you need to exclude groups based on a computed aggregate value, it must go in HAVING. Placing an aggregate function in WHERE produces a syntax error in standard SQL because aggregates are not yet computed at that point.
SELECT department, AVG(salary) AS avg_sal
FROM employees
WHERE salary IS NOT NULL
GROUP BY department
HAVING AVG(salary) > 50000;
-- WHERE removes individual rows with NULL salary before grouping.
-- HAVING then evaluates the average of surviving rows per department.
-- If a department had only NULL salaries, WHERE removes all its rows,
-- so no group is formed and HAVING never sees it.Practical tip
When debugging unexpected missing groups, run the query without the HAVING clause first and inspect the aggregate values. If any group shows NULL where you expected a number, that group is being silently dropped by UNKNOWN evaluation. Add a CASE expression that labels NULL aggregates as a distinct string before comparing, or use COUNT(column) alongside AVG(column) to detect groups with zero valid inputs.
Three-Valued Logic in Row Filtering
Oracle documentation states that any comparison condition involving NULL, other than IS NULL and IS NOT NULL, evaluates to UNKNOWN rather than TRUE or FALSE. This means the predicate salary > 50000 returns UNKNOWN when salary is NULL, and the row is excluded from the result just as if the predicate were FALSE. The critical difference is that UNKNOWN is not FALSE: applying NOT to FALSE yields TRUE, but applying NOT to UNKNOWN yields UNKNOWN again.
When WHERE contains a comparison that can evaluate to UNKNOWN, rows with NULL values in the compared column are silently removed. This is usually the intended behavior for numeric range filters, but it becomes a problem when the NULL represents missing data rather than an out-of-range value. The query author may assume all rows are accounted for, but rows with NULL salary are invisible to the grouping stage entirely.
SELECT department, COUNT(*) AS row_count
FROM employees
WHERE salary > 50000
GROUP BY department;
-- Rows with salary = NULL are excluded because NULL > 50000 is UNKNOWN.
-- A department with 100 employees but 40 NULL salaries shows only 60 rows.
-- The author may not realize 40 rows were silently dropped.NULL Propagation in Aggregates
Aggregate functions handle NULL inputs differently. SUM and AVG ignore NULL values in their input set, computing over only the non-NULL rows. If all input values are NULL, SUM returns NULL and AVG returns NULL. COUNT(column) counts only non-NULL values, while COUNT(*) counts all rows regardless of NULLs. This means a department where every salary is NULL will have AVG(salary) evaluate to NULL, not zero.
The consequence for HAVING is direct: when the aggregate produces NULL, any comparison against a numeric threshold yields UNKNOWN, and the group is excluded. The group is not reported as an error or flagged as anomalous; it simply disappears from the output. This is the mechanism by which HAVING hides data quality problems.
SELECT department,
COUNT(salary) AS non_null_count,
AVG(salary) AS avg_sal
FROM employees
GROUP BY department;
-- If a department has 50 employees all with NULL salary:
-- COUNT(salary) = 0, AVG(salary) = NULL
-- Then HAVING AVG(salary) > 50000 evaluates NULL > 50000 = UNKNOWN
-- The department vanishes from results with no indication of why.HAVING and Unknown Group States
A HAVING condition that evaluates to UNKNOWN causes the entire group to be excluded from the result set, behaving identically to FALSE for output purposes. However, the semantic meaning is different: FALSE means the group was evaluated and found not to meet the criterion, while UNKNOWN means the evaluation could not be completed because the input was missing. When these two cases produce the same visible outcome, the query consumer cannot distinguish a department with genuinely low salaries from a department with no salary data at all.
This is the core mechanism by which HAVING hides logic errors. A data pipeline that fails to populate salary values for a department will cause that department to disappear from reports. The report shows fewer departments, and no error is raised. The missing department looks identical to a department that legitimately has an average below the threshold.
SELECT department, AVG(salary) AS avg_sal
FROM employees
GROUP BY department
HAVING AVG(salary) > 50000;
-- Department 'Research' has all NULL salaries.
-- AVG(salary) = NULL, NULL > 50000 = UNKNOWN.
-- 'Research' is excluded. No error, no warning, no row in output.
-- The reader assumes 'Research' simply has low average salary.ANSI_NULLS Configuration Impact
Microsoft SQL Server provides a session-level setting called ANSI_NULLS that alters how comparison operators treat NULL values. When SET ANSI_NULLS is ON, which is the default in modern SQL Server versions, any comparison operator with a NULL operand returns UNKNOWN. When SET ANSI_NULLS is OFF, the equals and not-equals operators treat NULL as a known value that is equal to any other NULL, returning TRUE or FALSE instead of UNKNOWN.
This creates a portability risk. A query written with ANSI_NULLS OFF that uses salary = NULL to filter rows will behave differently on a server with ANSI_NULLS ON, where the same predicate returns UNKNOWN and excludes all rows. The HAVING clause inherits this behavior: a condition like AVG(salary) = NULL will match groups under ANSI_NULLS OFF but silently exclude all groups under ANSI_NULLS ON. Code that relies on this setting is fragile across environments.
-- SQL Server session setting
SET ANSI_NULLS ON;
SELECT department, AVG(salary) AS avg_sal
FROM employees
GROUP BY department
HAVING AVG(salary) > 50000;
-- With ANSI_NULLS ON: NULL > 50000 = UNKNOWN, group excluded.
-- With ANSI_NULLS OFF: same behavior for > operator (UNKNOWN still).
-- But HAVING AVG(salary) = NULL would match under OFF, not under ON.Logical Equivalence Pitfalls
A common mistake is assuming that negating a HAVING condition will capture the groups that the positive condition excluded. Oracle documentation explicitly states that NOT UNKNOWN evaluates to UNKNOWN, not TRUE. This means NOT (AVG(salary) > 50000) does not include groups where AVG(salary) is NULL; those groups still evaluate to UNKNOWN and are still excluded. The complement of a HAVING filter does not produce the set of previously missing groups.
This has practical consequences for debugging. If you write HAVING NOT (AVG(salary) > 50000) expecting to see the departments that were dropped by HAVING AVG(salary) > 50000, you will not see the NULL-averaging departments. They are invisible to both the positive and negative forms of the filter. The only way to surface them is to test explicitly for NULL with IS NULL.
SELECT department, AVG(salary) AS avg_sal
FROM employees
GROUP BY department
HAVING NOT (AVG(salary) > 50000);
-- This does NOT return departments with NULL average salary.
-- NOT UNKNOWN = UNKNOWN, so those groups are still excluded.
-- To find them you need: HAVING AVG(salary) IS NULLDiagnostic Strategy for Hidden Errors
To determine whether missing groups are due to intentional filtering or accidental data loss, compare the row counts at three stages: total rows in the table, rows surviving WHERE, and rows contributing to each group. If WHERE removes rows containing NULLs that should have been retained, the group sizes will be smaller than expected. If a group has zero contributing rows after WHERE, it never appears in the output at all, which is different from appearing but being dropped by HAVING.
A practical diagnostic query removes the HAVING clause and adds a CASE expression that labels NULL aggregates. This separates the three possible states: the group met the threshold, the group did not meet the threshold, and the group had no valid data to evaluate. Running this without HAVING reveals which groups would have been silently dropped.
SELECT department,
COUNT(salary) AS valid_rows,
AVG(salary) AS avg_sal,
CASE
WHEN AVG(salary) IS NULL THEN 'NO_DATA'
WHEN AVG(salary) > 50000 THEN 'ABOVE_THRESHOLD'
ELSE 'BELOW_THRESHOLD'
END AS status
FROM employees
WHERE salary IS NOT NULL
GROUP BY department;
-- Groups with zero valid_rows will not appear because WHERE removed all rows.
-- To see them, remove WHERE and use HAVING with IS NULL check.Best Practices for Robust Filtering
Use explicit IS NULL and IS NOT NULL predicates wherever the presence or absence of data is semantically meaningful. Never rely on comparison operators to handle NULLs, because their behavior depends on three-valued logic and, in SQL Server, on session configuration. When a NULL aggregate represents a data quality issue rather than a valid filtering outcome, surface it explicitly with IS NULL in HAVING or use COALESCE to assign a sentinel value that can be distinguished from real data.
For cross-database portability, avoid relying on vendor-specific NULL semantics. Oracle treats empty strings as NULL, which can cause unexpected UNKNOWN results in string comparisons. SQL Server's ANSI_NULLS setting changes comparison behavior between sessions. PostgreSQL follows the standard three-valued logic consistently. Writing queries that use only IS NULL, IS NOT NULL, and COALESCE for NULL handling produces deterministic results across all these engines.
SELECT department,
COALESCE(AVG(salary), -1) AS avg_sal_or_missing
FROM employees
GROUP BY department
HAVING COALESCE(AVG(salary), -1) > 50000
OR COALESCE(AVG(salary), -1) = -1;
-- COALESCE converts NULL to -1, a sentinel that is always comparable.
-- The OR branch explicitly includes departments with no valid salary data.
-- This makes the filtering logic deterministic regardless of NULL handling.Things to check
- WHERE filters rows before grouping; HAVING filters groups after aggregation; placing an aggregate in WHERE causes a syntax error in standard SQL.
- A comparison with NULL returns UNKNOWN, not FALSE; NOT UNKNOWN also returns UNKNOWN, so negating a HAVING condition does not recover NULL-evaluating groups.
- AVG and SUM over all-NULL inputs return NULL; COUNT(column) returns 0; COUNT(*) returns the row count regardless of NULLs.
- SQL Server ANSI_NULLS ON makes NULL comparisons return UNKNOWN; ANSI_NULLS OFF makes equals and not-equals treat NULL as a comparable value, creating portability risk.
- A HAVING condition evaluating to UNKNOWN silently excludes the group with no error, making missing data indistinguishable from below-threshold data.
- Diagnostic queries should remove HAVING and add CASE labels for NULL aggregates to reveal which groups were being silently dropped.
Where this applies
This article addresses logical correctness and the mechanism by which HAVING hides data quality issues through three-valued logic. It does not cover performance optimization of WHERE versus HAVING placement, index selection, or query plan differences beyond the logical execution order. The treatment of NULL semantics assumes standard SQL three-valued logic as documented by Oracle and SQL Server; vendor-specific extensions from PostgreSQL, MySQL, or other engines are not detailed. Oracle's behavior of treating empty strings as NULL is noted but not explored as a separate failure mode. The ANSI_NULLS discussion is limited to SQL Server and does not address equivalent settings in other products.