WHERE and HAVING clauses are both used to filter data in SQL, but their scopes are different: the WHERE clause filters single rows, and the HAVING clause filters grouped result sets. The WHERE clause is applied before grouping and affects the result rows of the aggregate function; the HAVING clause is applied after grouping and affects grouped rows rather than individual rows. The WHERE clause can filter any column, while the HAVING clause can only filter the results of aggregate functions.
The difference between WHERE and HAVING clauses
In SQL queries, WHERE and HAVING clauses are used for filtering rows of data, but they have different scopes and uses.
WHERE clause
HAVING clause
Comparison table
Features | WHERE clause | HAVING sub Sentence |
---|---|---|
Scope | Single line | Group |
Application timing | Before grouping | After grouping |
Influence | Aggregation function result row | Group row |
Example
The following query uses the WHERE clause to filter out orders with sales exceeding 1,000:
<code class="sql">SELECT * FROM orders WHERE sales_amount > 1000;</code>
The following query uses HAVING The clause filters out all customers whose average sales exceed 1000:
<code class="sql">SELECT customer_id, AVG(sales_amount) AS avg_sales FROM orders GROUP BY customer_id HAVING avg_sales > 1000;</code>
Notes
The above is the detailed content of The difference between where and having in sql. For more information, please follow other related articles on the PHP Chinese website!