HAVING Clause

Description

The HAVING clause is used to filter the results produced by GROUP BY based on the specified condition. It is often used in conjunction with a GROUP BY clause.

Syntax

  1. HAVING boolean_expression

Parameters

  • boolean_expression

    Specifies any expression that evaluates to a result type boolean. Two or more expressions may be combined together using the logical operators ( AND, OR ).

    Note

    The expressions specified in the HAVING clause can only refer to:

    1. Constants
    2. Expressions that appear in GROUP BY
    3. Aggregate functions

Examples

  1. CREATE TABLE dealer (id INT, city STRING, car_model STRING, quantity INT);
  2. INSERT INTO dealer VALUES
  3. (100, 'Fremont', 'Honda Civic', 10),
  4. (100, 'Fremont', 'Honda Accord', 15),
  5. (100, 'Fremont', 'Honda CRV', 7),
  6. (200, 'Dublin', 'Honda Civic', 20),
  7. (200, 'Dublin', 'Honda Accord', 10),
  8. (200, 'Dublin', 'Honda CRV', 3),
  9. (300, 'San Jose', 'Honda Civic', 5),
  10. (300, 'San Jose', 'Honda Accord', 8);
  11. -- `HAVING` clause referring to column in `GROUP BY`.
  12. SELECT city, sum(quantity) AS sum FROM dealer GROUP BY city HAVING city = 'Fremont';
  13. +-------+---+
  14. | city|sum|
  15. +-------+---+
  16. |Fremont| 32|
  17. +-------+---+
  18. -- `HAVING` clause referring to aggregate function.
  19. SELECT city, sum(quantity) AS sum FROM dealer GROUP BY city HAVING sum(quantity) > 15;
  20. +-------+---+
  21. | city|sum|
  22. +-------+---+
  23. | Dublin| 33|
  24. |Fremont| 32|
  25. +-------+---+
  26. -- `HAVING` clause referring to aggregate function by its alias.
  27. SELECT city, sum(quantity) AS sum FROM dealer GROUP BY city HAVING sum > 15;
  28. +-------+---+
  29. | city|sum|
  30. +-------+---+
  31. | Dublin| 33|
  32. |Fremont| 32|
  33. +-------+---+
  34. -- `HAVING` clause referring to a different aggregate function than what is present in
  35. -- `SELECT` list.
  36. SELECT city, sum(quantity) AS sum FROM dealer GROUP BY city HAVING max(quantity) > 15;
  37. +------+---+
  38. | city|sum|
  39. +------+---+
  40. |Dublin| 33|
  41. +------+---+
  42. -- `HAVING` clause referring to constant expression.
  43. SELECT city, sum(quantity) AS sum FROM dealer GROUP BY city HAVING 1 > 0 ORDER BY city;
  44. +--------+---+
  45. | city|sum|
  46. +--------+---+
  47. | Dublin| 33|
  48. | Fremont| 32|
  49. |San Jose| 13|
  50. +--------+---+
  51. -- `HAVING` clause without a `GROUP BY` clause.
  52. SELECT sum(quantity) AS sum FROM dealer HAVING sum(quantity) > 10;
  53. +---+
  54. |sum|
  55. +---+
  56. | 78|
  57. +---+