HAVING clause in BigQuery

The HAVING clause in BigQuery is used to filter records that have been grouped using a GROUP BY clause. It is similar to the WHERE clause, but it works on groups rather than individual rows.

The HAVING clause is commonly used with aggregate functions such as COUNT, SUM, AVG, MAX, and MIN.

SQL Syntax

SELECT column1, column2, aggregate_function(column3)
FROM table_name
WHERE condition
GROUP BY column1, column2
HAVING aggregate_function(column3) condition;   

Example: Let’s have the Employees table. To view all the records, execute the following query.

SQL

SELECT * FROM `ashishcoder.Coding_Dataset.employees`;    

The output of the above query is shown below:

HAVING clause in BigQuery

Let’s group the employee salary by department and then filter out the department that is not equal to Electronics.

SQL

SELECT Department, SUM(Salary) AS Total_Salary
FROM `ashishcoder.Coding_Dataset.employees`
GROUP BY Department
HAVING Department NOT IN ("Electronics");    

The output of the above query is shown below:

HAVING clause in BigQuery