The "GROUP BY" clause is used in SQL to group rows that have the same values in specified columns into summary rows. It's typically used in conjunction with aggregate functions like COUNT, SUM, AVG, MAX, and MIN to perform calculations on groups of rows rather than individual rows.
When you use "GROUP BY," the result set is divided into groups based on the values in the specified columns. Each group is then processed separately, and aggregate functions operate on each group, producing a single result for each group.
Here's a basic example using a hypothetical "Orders" table to find the total order amount for each customer:
SELECT customer_id, SUM(order_amount)
FROM orders
GROUP BY customer_id;
In this query, we are grouping orders by the "customer_id" column, and then using the SUM function to calculate the total order amount for each customer.
The "HAVING" clause is used in SQL to filter the result set after it has been grouped by the "GROUP BY" clause. It allows you to apply conditions to the grouped data.
Unlike the "WHERE" clause, which filters individual rows before grouping, the "HAVING" clause filters the result set after grouping, based on the results of aggregate functions.
Here's an example extending the previous query to find customers who have placed orders with a total amount greater than $1,000:
SELECT customer_id, SUM(order_amount)
FROM orders
GROUP BY customer_id
HAVING SUM(order_amount) > 1000;
In this query, we first group the orders by "customer_id" and then use the "HAVING" clause to filter out groups where the total order amount is greater than $1,000.
In summary, the "GROUP BY" clause is used for grouping rows based on specific columns, and aggregate functions are applied to each group. The "HAVING" clause is used to filter the grouped results based on conditions involving aggregate functions. This combination allows you to perform complex analysis and summaries on your data in SQL.
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
In this query, we are grouping orders by the "customer_id" column, and then using the SUM function to calculate the total order amount for each customer.
In this query, we first group the orders by "customer_id" and then use the "HAVING" clause to filter out groups where the total order amount is greater than $1,000.
In summary, the "GROUP BY" clause is used for grouping rows based on specific columns, and aggregate functions are applied to each group. The "HAVING" clause is used to filter the grouped results based on conditions involving aggregate functions. This combination allows you to perform complex analysis and summaries on your data in SQL.