Home  >  Article  >  Database  >  The difference between where and having in sql

The difference between where and having in sql

下次还敢
下次还敢Original
2024-05-01 21:42:34628browse

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 in sql

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

  • Applies to a single row of the table.
  • Used to filter out rows that meet specified conditions.
  • Apply before data grouping.
  • Affects the result rows of aggregate functions.

HAVING clause

  • Apply to the grouped result set.
  • Used to filter out groups that meet specified conditions.
  • Apply after data grouping.
  • Affects grouped rows rather than individual rows.

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 WHERE clause can filter any column, while the HAVING clause only Ability to filter the results of aggregate functions.
  • The HAVING clause is usually used together with the GROUP BY clause, while the WHERE clause can be used independently.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn