HAVING
HAVING allows filtering of rows that were created using GROUP BY.
Syntax
sql
SELECT ...
FROM ...
GROUP BY ...
HAVING predicate
[ ... ]
predicateParameters
predicate: A boolean expression.
Usage Notes
The condition specified in the
HAVINGclause applies to expressions produced byGROUP BY. Therefore, the same restrictions that apply toGROUP BYexpressions also apply toHAVING.The predicate may refer only to:
- Constants
- Expressions listed in the
GROUP BYclause - Aggregate functions
Expressions in the
SELECTlist can be referenced by the column alias defined in that list.
Example 1
sql
WITH
t1 AS (
SELECT 1 AS col1, 2 AS col2
UNION ALL
SELECT 1 AS col1, 3 AS col2
UNION ALL
SELECT 2 AS col1, 4 AS col2
UNION ALL
SELECT 2 AS col1, 5 AS col2
UNION ALL
SELECT 3 AS col1, 6 AS col2
)
SELECT col1, SUM(col2) AS sum_col2
FROM t1
GROUP BY col1
HAVING SUM(col2) < 9;+------+----------+
| COL1 | SUM_COL2 |
+------+----------+
| 1 | 5 |
| 3 | 6 |
+------+----------+Example 2
sql
WITH
t1 AS (
SELECT 1 AS col1, 2 AS col2
UNION ALL
SELECT 1 AS col1, 3 AS col2
UNION ALL
SELECT 2 AS col1, 4 AS col2
UNION ALL
SELECT 2 AS col1, 5 AS col2
UNION ALL
SELECT 3 AS col1, 6 AS col2
)
SELECT col1, SUM(col2) AS sum_col2
FROM t1
GROUP BY col1
HAVING COUNT(*) > 1;+------+----------+
| COL1 | SUM_COL2 |
+------+----------+
| 1 | 5 |
| 2 | 9 |
+------+----------+