The Having clause in SQL is typically used with SQL Queries to provide a more precise condition for a statement. You can use it to mention conditions in Group by based SQL queries, such as the WHERE clause which is used with SELECT query.
Below is the syntax for the HAVING clause;
SELECT column_name, function(column_name) FROM table_name WHERE column_name condition GROUP BY column_name HAVING function(column_name) condition
Let’s consider the Sale table below:
oid | order_name | previous_balance | customer |
---|---|---|---|
11 | ord1 | 2000 | Alex |
12 | ord2 | 1000 | Adam |
13 | ord3 | 2000 | Mike |
14 | ord4 | 1000 | Unaoi |
15 | ord5 | 2000 | Alex |
Take, for instance, we want to find the customer whose previous_balance sum is more than 3000. We can use the SQL query below,
SELECT *
FROM sale GROUP BY customer
HAVING sum(previous_balance) > 3000
The result is shown in the table below:
oid | order_name | previous_balance | customer |
---|---|---|---|
11 | ord1 | 2000 | Alex |
Conclusively, the basic objective of the above SQL query was to find out the name of the customer who has had a previous_balance more than 3000, with respect to all the previous sales made to the customer, therefore the first row in the table for customer Alex is obtained.