Home > Database > Mysql Tutorial > HAVING vs. WHERE in SQL: When to Use Each Clause for Data Filtering?

HAVING vs. WHERE in SQL: When to Use Each Clause for Data Filtering?

Susan Sarandon
Release: 2025-01-14 17:11:45
Original
673 people have browsed it

HAVING vs. WHERE in SQL: When to Use Each Clause for Data Filtering?

The difference between HAVING and WHERE clauses in SQL SELECT statement

In a SQL SELECT statement, the HAVING and WHERE clauses serve different purposes in data filtering. Understanding their usage is critical to obtaining accurate query results.

HAVING clause

HAVING clause is applied after aggregation using GROUP BY clause. It filters grouped rows based on a condition applied to the aggregated value. For example:

<code class="language-sql">SELECT City, COUNT(1) AS CNT
FROM Address
WHERE State = 'MA'
GROUP BY City
HAVING COUNT(1) > 5</code>
Copy after login

This query returns a table containing cities in Massachusetts and their number of addresses (more than 5).

WHERE clause

In contrast, the WHERE clause filters rows before aggregation. It evaluates the condition on individual rows and selects only the rows that satisfy the condition. For example:

<code class="language-sql">SELECT City, COUNT(1) AS CNT
FROM Address
WHERE State = 'MA' AND City LIKE '%ton'
GROUP BY City</code>
Copy after login

This query returns a table containing the number of cities in Massachusetts (with names ending in "ton") and their addresses.

Key differences

The main difference between HAVING and WHERE is when they are applied:

  • HAVING filters aggregated data after grouping.
  • WHERE Filter individual rows before grouping.

By leveraging this distinction, developers can precisely manipulate and filter data in SQL SELECT statements to retrieve the desired results.

The above is the detailed content of HAVING vs. WHERE in SQL: When to Use Each Clause for Data Filtering?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template