TATECHATLAS
◎ English
Data & databases / Guide

SQL: WHERE vs HAVING - Difference in Row and Group Filtering

A detailed technical breakdown of the differences between WHERE and HAVING clauses, focusing on execution order, aggregate function compatibility, and performance optimization strategies.

On this page

The fundamental difference lies in the timing of application: WHERE filters individual rows before any grouping occurs (pre-GROUP BY), whereas HAVING filters groups of rows after they have been aggregated (post-GROUP BY). Consequently, aggregate functions like SUM() or AVG() cannot be used in a WHERE clause but are the primary purpose of the HAVING clause.

The SQL Query Execution Order

To master the distinction between WHERE and HAVING, one must understand the logical processing order of a SQL statement. A query does not execute in the order it is written (SELECT, FROM, WHERE...). Instead, the database engine follows a specific pipeline. It begins with the FROM clause to identify the source tables and perform JOIN operations. Next, the WHERE clause is applied to filter the raw rows from these tables. Only after this filtering is the data passed to the GROUP BY clause, which organizes rows into buckets. The HAVING clause then filters these buckets based on aggregate results. Finally, the SELECT clause determines which columns and computed aggregates are returned to the user.

Understanding this sequence is critical because it explains why certain errors occur. If you attempt to filter by an aggregate value in the WHERE clause, the engine throws an error because the grouping and aggregation steps have not yet happened. The WHERE clause is strictly a row-level filter, operating on the raw data stream before any mathematical summarization takes place.

This is logical processing order, not a guaranteed physical execution schedule. PostgreSQL may push a legal predicate on a grouping key below aggregation. Use the clauses to express the intended row or group condition, then inspect EXPLAIN when discussing performance.

-- Logical processing model, not a physical execution plan:
-- FROM / JOIN -> WHERE -> GROUP BY -> HAVING -> SELECT -> ORDER BY

When to Use the WHERE Clause

Use WHERE for a condition on individual sales rows. To select only 2023, the example uses sale_date >= DATE '2023-01-01' and sale_date < DATE '2024-01-01'. A lower bound alone would also admit 2024 and later years. The half-open interval includes the whole final day for a date or timestamp column.

An aggregate of the current query level cannot be used directly in WHERE. An aggregate computed by a subquery is a separate query-level result and can be filtered by an outer WHERE. For timestamp with time zone, define the business time zone and use explicit boundaries consistent with that definition.

SELECT product_name, price
FROM sales
WHERE sale_date >= DATE '2023-01-01'
  AND sale_date < DATE '2024-01-01';

When to Use the HAVING Clause

The HAVING clause is specifically engineered to work with aggregated data. Once rows are grouped together, the database calculates summary values like sums, averages, or counts for each group. The HAVING clause allows you to apply conditional logic to these summary values. For instance, if you need to find only those product categories where the total sales volume exceeds $10,000, you must use HAVING because 'total sales volume' is a result of an aggregation, not a property of a single row.

HAVING expresses a condition on a group, such as SUM(amount) > 10000. It is not inherently always slower than WHERE. A grouping-key predicate can sometimes be pushed down by the optimizer; an aggregate predicate must retain its group-level meaning. Choose the clause for semantics, and compare plans only for equivalent queries.

SELECT category, SUM(amount) AS total
FROM orders
GROUP BY category
HAVING SUM(amount) > 10000; -- Filters groups AFTER aggregation

Comparative Analysis: WHERE vs HAVING

The first query below counts login rows for each user and keeps users with more than five logins. The commented second query is invalid for the illustrated logs schema: event_type is neither grouped nor aggregated, and no functional dependency is established. It is an example of a grouping error, not a slower alternative.

In PostgreSQL, a nonaggregated HAVING reference must be a grouping expression or satisfy the documented functional-dependency rule. Adding event_type to GROUP BY changes the groups and may change the task. SQL validity, equivalent results and runtime cost are three distinct checks; one cannot be inferred from another.

SELECT user_id, COUNT(*) AS login_count
FROM logs
WHERE event_type = 'login'
GROUP BY user_id
HAVING COUNT(*) > 5;

-- Invalid for the illustrated schema; grouping error, not a speed comparison:
-- SELECT user_id, COUNT(*) FROM logs GROUP BY user_id
-- HAVING event_type = 'login' AND COUNT(*) > 5;

Avoiding Logical Errors in Complex Queries

Keep the three predicate roles separate. ON controls which rows match during an outer join and whether unmatched rows are preserved. WHERE filters rows in the joined table. HAVING filters groups after aggregation. Moving a nullable-side predicate from ON to WHERE can discard unmatched rows; that is an outer-join semantics issue, not an effect of HAVING.

SELECT region, AVG(temperature)
FROM weather_data
WHERE year = 2023 -- Removes irrelevant years before the expensive AVG calculation
GROUP BY region
HAVING AVG(temperature) > 25; -- Filters regions based on the calculated average

Interaction with JOIN Operations

The placement of filters in relation to JOINs is a subtle but vital concept. In a JOIN operation, you can use the ON clause to define how tables are linked. You can also include additional conditions in the ON clause. These conditions are processed during the join itself. For INNER JOINs, placing a condition in the ON clause versus the WHERE clause often yields the same result, but for OUTER JOINs (LEFT, RIGHT, FULL), the distinction is massive. A condition in the ON clause limits which rows are matched, while a condition in the WHERE clause limits the final result set.

When combining JOIN, WHERE, and HAVING, the order of operations becomes: 1. The JOIN condition (ON) determines the initial combined set. 2. The WHERE clause filters that combined set. 3. The GROUP BY organizes the remaining rows. 4. The HAVING clause filters the groups. Misunderstanding this pipeline leads to queries that either return too much data (inefficiency) or the wrong data (logical error).

SELECT c.id, c.name, SUM(o.amount)
FROM customers c
LEFT JOIN orders o ON c.id = o.customer_id 
  AND o.status = 'completed' -- This condition is part of the join logic
GROUP BY c.id, c.name
HAVING SUM(o.amount) > 100;

Practical Implementation: Sales Analysis

Consider a real-world scenario: finding high-value customers in a specific category. Suppose you need to identify customers who made more than 3 purchases in the 'Electronics' category during the year 2023. This requires a multi-stage filtering process. First, you must filter the raw sales data to include only 'Electronics' and only dates within 2023 using the WHERE clause. This reduces the dataset to only relevant transactions.

The sales example defines one row as one order and assumes order_id is non-null. The same half-open 2023 interval is used for date and timestamp values; the upper boundary is the start of 2024. If an order has several lines, COUNT(order_id) counts lines instead, so first define the required granularity or use an appropriate distinct count.

SELECT customer_id, COUNT(order_id) AS order_count
FROM sales
WHERE category = 'Electronics'
  AND order_date >= DATE '2023-01-01'
  AND order_date < DATE '2024-01-01'
GROUP BY customer_id
HAVING COUNT(order_id) > 3;

Summary and Quick Reference Guide

To summarize, the choice between WHERE and HAVING is determined by whether you are filtering individual records or summarized groups. Use WHERE for standard column comparisons (e.g., id = 10, status = 'active') to optimize performance by reducing the input to the aggregation engine. Use HAVING for conditions involving aggregate functions (e.g., SUM(total) > 500, COUNT(*) > 1) to filter the results of a GROUP BY operation.

Prefer WHERE for the intended row filter and HAVING for the intended aggregate filter. This improves clarity without promising a universal speedup. Verify grouping rules and period boundaries, and compare a real execution plan before making a performance claim.

-- Quick Reference Cheat Sheet:
-- WHERE: Operates on individual rows; cannot use aggregate functions; executes BEFORE GROUP BY.
-- HAVING: Operates on grouped rows; designed for aggregate functions; executes AFTER GROUP BY.

Things to check

  • In PostgreSQL, a nonaggregated HAVING reference must be a grouping expression or satisfy the documented functional-dependency rule. Adding event_type to GROUP BY changes the groups and may change the task. SQL validity, equivalent results and runtime cost are three distinct checks; one cannot be inferred from another.
  • Use WHERE for a condition on individual sales rows. To select only 2023, the example uses sale_date >= DATE '2023-01-01' and sale_date < DATE '2024-01-01'. A lower bound alone would also admit 2024 and later years. The half-open interval includes the whole final day for a date or timestamp column.
  • Prefer WHERE for the intended row filter and HAVING for the intended aggregate filter. This improves clarity without promising a universal speedup. Verify grouping rules and period boundaries, and compare a real execution plan before making a performance claim.

An aggregate of the current query level cannot be used directly in WHERE. An aggregate computed by a subquery is a separate query-level result and can be filtered by an outer WHERE. For timestamp with time zone, define the business time zone and use explicit boundaries consistent with that definition. In PostgreSQL, a nonaggregated HAVING reference must be a grouping expression or satisfy the documented functional-dependency rule. Adding event_type to GROUP BY changes the groups and may change the task. SQL validity, equivalent results and runtime cost are three distinct checks; one cannot be inferred from another.

Sources

  1. PostgreSQL: table expressions ↗
  2. PostgreSQL: aggregate functions ↗
Back to top ↑