Updated on 2026-11-06 GMT+08:00

HAVING

Function

The HAVING clause is used to filter the results after a GROUP BY operation. Unlike WHERE, HAVING can use aggregate functions as filter conditions. Spark 4.0 enhances the subquery capabilities within the HAVING clause.

Syntax

SELECT [ ALL | DISTINCT ] projectItem [, ...] FROM table_reference
  GROUP BY { expression [, ...] | GROUPING SETS (...) | ROLLUP (...) | CUBE (...) }
  HAVING boolean_expression

Parameters

Parameter

Description

ALL

Returns all rows, including duplicate rows. This is the default option.

DISTINCT

Removes duplicate rows from the result set.

GROUP BY

Groups by the specified expression. Supports GROUPING SETS, ROLLUP, and CUBE extensions.

HAVING

Filters the grouped results. Conditions can use aggregate functions and subqueries.

boolean_expression

The filter condition expression, typically containing aggregate functions. Can include subqueries.

Precautions

  • The table being queried must already exist. Otherwise, an error will occur.
  • The position of the subquery and the aggregate function in the HAVING clause cannot be swapped. The aggregate function can appear on either side of the comparison operator (e.g., AVG(score) > 80 or 80 < AVG(score)), and their positions are interchangeable.
  • Difference between HAVING and WHERE: WHERE filters rows before grouping, while HAVING filters groups after grouping.

Examples

Basic HAVING filtering:

SELECT class_id, AVG(score) AS avg_score FROM student
   GROUP BY class_id
   HAVING AVG(score) > 80; 

Subquery as a HAVING condition:

SELECT name FROM student_info
   GROUP BY name
   HAVING count(name) = (SELECT count(*) FROM course_info); 

Used with ROLLUP:

SELECT group_id, job, SUM(salary) FROM group_test
   GROUP BY ROLLUP (group_id, job)
   HAVING SUM(salary) > 10000;