SOQL Having Vs WHERE

R

Simple Explanation

HAVING in SOQL works similarly to WHERE, but there is an important difference:

  • WHERE filters records before the data is grouped.

  • HAVING filters records after the data is grouped.

This is the difference between HAVING and WHERE


Basic Query

For Example Let's take this 6 Accounts.

Account Name BillingCountry AnnualRevenue
Acc A USA 60,000
Acc B USA 50,000
Acc C USA 20,000
Acc D India 40,000
Acc E India 70,000
Acc F Canada 200,000

Case 1: Using WHERE

If you wanna query billing country and number of accounts that are individually above 100K in Annual Revenue

SELECT BillingCountry, COUNT(Id) accCount
FROM Account
WHERE AnnualRevenue > 100000
GROUP BY BillingCountry

this will be the result

BillingCountry accCount
Canada 1

Case 2 : Using HAVING

If you wanna query billing country and number of accounts that combinely contribute above 100K in Annual Revenue

SELECT BillingCountry, COUNT(Id) accCount
FROM Account
GROUP BY BillingCountry
HAVING SUM(AnnualRevenue) > 100000

BillingCountry accCount
USA 3
India 2
Canada 1

Calculation

USA = 60K + 50K + 20K = 130K

India = 40K + 70K = 110K

Canada = 200K