A GROUP BY query in SQL is used to arrange identical data into groups. It is often used in conjunction with aggregate functions (like COUNT(), SUM(), AVG(), etc.) to perform calculations on each group of data.
Example
Consider a table named sales with the following columns: product_id, quantity, and price.
SELECT product_id, SUM(quantity) AS total_quantity
FROM sales
GROUP BY product_id;
Result
This query will return a result set that shows each unique product_id along with the total quantity sold for each product. The output might look like this:
| product_id | total_quantity |
|---|---|
| 1 | 100 |
| 2 | 150 |
| 3 | 200 |
In this example, the GROUP BY clause groups the rows in the sales table by product_id, and the SUM(quantity) calculates the total quantity for each product.
