Junior — Middle
What are the reasons for using the GROUP BY operator when performing aggregate queries in SQL?
sobes.tech AI
Answer from AI
The GROUP BY operator in SQL is used to group rows with the same values in specified columns, allowing aggregate functions (such as SUM, COUNT, AVG, MAX, MIN) to be applied to each group separately. This is necessary when you want to obtain summary data by categories or groups, rather than for the entire table.
For example, if there is a sales table and you want to find the total sales amount for each salesperson, GROUP BY will group the records by salesperson, and the aggregate function will calculate the sum for each group:
SELECT seller_id, SUM(amount) AS total_sales
FROM sales
GROUP BY seller_id;
Without GROUP BY, the aggregate function would be applied to the entire table, not by groups. Thus, GROUP BY allows structuring and analyzing data by categories.