Member-only story

SQL Filters: WHERE vs. HAVING in Data Filtering

btd
2 min readNov 13, 2023

--

In SQL, both the WHERE and HAVING clauses are used to filter data, but they are used in different contexts and with different purposes.

I. WHERE Clause:

  • The WHERE clause is used with the SELECT, UPDATE, DELETE, and INSERT statements to filter rows based on a specified condition.
  • It is primarily used for filtering rows before they are grouped and aggregated.
  • It operates on individual rows before any grouping or aggregation takes place.
  • Commonly used for conditions involving columns present in the individual rows.
SELECT column1, column2
FROM table_name
WHERE condition;

II. HAVING Clause:

  • The HAVING clause is used with the SELECT statement and is specifically used with aggregate functions like COUNT, SUM, AVG, etc.
  • It is used to filter the results of a grouped query, specifying conditions on the result of aggregate functions.
  • It operates on grouped rows, after the GROUP BY clause, and filters the result set based on aggregated values.
  • Commonly used for conditions involving the result of aggregate functions.
SELECT column1, column2, aggregate_function(column3)
FROM…

--

--

btd
btd

No responses yet