The SQL HAVING clause is used in combination with the GROUP BY clause to filter the results of aggregate functions applied to groups of rows. While the WHERE clause filters individual rows before they are grouped, the HAVING clause filters groups of rows after they have been grouped. The basic syntax of the HAVING clause is as follows:
SELECT column1, column2, ..., aggregate_function(column_name)
FROM table_name
WHERE condition
GROUP BY column1, column2, ...
HAVING condition
column1, column2, ...
: Columns you want to include in the result set.aggregate_function(column_name)
: Aggregate functions like COUNT, SUM, AVG, MAX, or MIN applied to specific columns.table_name
: Name of the table you're querying.condition
: Conditions to filter rows before grouping (in the WHERE clause) and conditions to filter groups after grouping (in the HAVING clause).GROUP BY column1, column2, ...
: Specifies the columns by which to group the result set.For example, let's say you have a table called orders
with columns customer_id
and total_amount
. If you want to find customers who have spent more than a certain amount, say $1000, you can use the HAVING clause like this:
SELECT customer_id, SUM(total_amount) AS total_spent
FROM orders
GROUP BY customer_id
HAVING SUM(total_amount) > 1000;
In this example:
customer_id
column and calculate the sum of total_amount
for each customer.GROUP BY customer_id
clause ensures that the result set is grouped by the customer_id
column.HAVING SUM(total_amount) > 1000
condition filters out groups where the total amount spent is less than or equal to $1000.The result will contain each customer_id
along with the corresponding total amount spent by that customer, but only for customers who have spent more than $1000.