Sobes.tech
Junior — Middle

What is the main task of the GROUP BY operator in SQL and when is it used?

sobes.tech AI

Answer from AI

The GROUP BY operator in SQL is used to group rows of a table based on one or more columns. Its main purpose is to aggregate data, allowing the application of aggregate functions (such as COUNT, SUM, AVG, MAX, MIN) to each group separately.

It is used when you need to obtain summary information, for example, the number of orders per customer, average income by department, etc.

Example:

SELECT department, COUNT(*) AS employee_count
FROM employees
GROUP BY department;

This query groups employees by department and counts the number of employees in each department.