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

Using HAVING in GROUP BY

Function

Uses the HAVING clause to filter after grouping a table.

Syntax

SELECT attr_expr_list FROM table_reference
 GROUP BY groupby_expression[, groupby_expression... ]
 HAVING having_expression;

Keywords

groupby_expression: Can be a single field, multiple fields, or an aggregate function, string function, etc.

Precautions

  • The table to be grouped must already exist. Otherwise, an error is reported.
  • If the filter condition is affected by the query results of GROUP BY, the WHERE clause cannot be used for filtering. Instead, the HAVING clause must be used. If HAVING is used in conjunction with GROUP BY, the data is first grouped by GROUP BY, and then filtered in the HAVING clause. The HAVING clause supports arithmetic operations, aggregate functions, etc.

Example

First, group the transactions table by num. Then, use the HAVING clause to filter the query results. Records where the maximum value of the product of price and amount is greater than 5000 will be selected. Return the corresponding num and the maximum value of the product of price and amount.

SELECT num, max(price*amount) FROM transactions
   WHERE time > '2016-06-01'
   GROUP BY num
   HAVING max(price*amount)>5000;