Skip to content

WHERE and HAVING in BigQuery

WHERE

The WHERE clause filters the results of the FROM clause. It filters rows based on a specified condition or conditions.

Single-Condition

For example, I want to find all products whose price is under 4.00.

SELECT Name, Price  FROM `instruction-415216.examples.ivys_shop` 
WHERE Price  <  5.00    #  this is a condition

It returned 31 results. Here we only show 5 records.

RowNamePrice
1Kiwi0.85
2Kiwi2.7
3Peach1.02
4Peach0.72
5Banana1.24

Multi-Condition : AND

For example, I want to find all products whose price is under 3.00 and has been sold at least 20 pieces.

SELECT Name,Price,Sold  FROM `instruction-415216.examples.ivys_shop` 
WHERE Price  <  3.00 AND  Sold >= 20    # multiple conditions

It returned 14 results and here we only show 5 records.

RowNamePriceSold
1Kiwi0.8557
2Kiwi2.722
3Peach1.0271
4Peach0.7244
5Pineapple2.5724

Multi-Condition : OR

Another example, what if I want to find all products whose name is “Peach” or “Pineapple”?

SELECT Name,  Price,  Sold  FROM `instruction-415216.examples.ivys_shop` 
WHERE Name  =  "Peach" OR Name  =  "Pineapple" 
# It can be written in this way:  WHERE NAME IN ("Peach","Pineapple")
RowNamePriceSold
1Peach1.0271
2Peach4.337
3Peach4.125
4Peach0.7244
5Pineapple8.841
6Pineapple7.863
7Pineapple5.312
8Pineapple2.5724
9Pineapple9.8552

HAVING

The HAVING clause filters the results produced by GROUP BY or aggregation. GROUP BY or aggregation must be present in the query. 

For example, I want to find all vegetables whose price is above 8.00.

Notice, the WHERE condition is before GROUP BY and the HAVING condition is after GROUP BY

SELECT Name,Price FROM `instruction-415216.examples.ivys_shop` 
WHERE  Category  = 'Vegetable'  # the  WHERE  condition  is before GROUP BY
GROUP BY Name, Price
HAVING Price  > 8              # the having  condition  is after  GROUP BY
RowNamePrice
1Onion9.07
2Potato9.98
3Potato8.06
4Tomato9.51
5Broccoli9.55
6Broccoli9.35
7Cucumber9.72
8Zucchini8.72
9Zucchini9.64

The HAVING clause can have multiple conditions, too.

SELECT Name, Price, Sold FROM `instruction-415216.examples.ivys_shop` 
WHERE  Category  = 'Vegetable'
GROUP BY Name, Price, Sold
HAVING Price  > 8 AND Sold  > 30      # multiple condition
RowNamePriceSold
1Potato9.9870
2Cucumber9.7231
3Zucchini8.7235