Sobes.tech
Junior

What is the 'GROUP BY' operator and what role does it play in SQL?

sobes.tech AI

Answer from AI

GROUP BY is used in SQL to group rows with identical values in one or more columns.

Its roles:

  • Data aggregation: Allows applying aggregate functions such as COUNT, SUM, AVG, MIN, MAX to each group. This enables obtaining summarized data by categories.
  • Getting unique combinations: Can be used to identify unique combinations of values in specified columns.
  • Ordering results: Often used in conjunction with ORDER BY to sort grouped results.

Example of usage:

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

Here, GROUP BY department groups rows by the value in the department column, and COUNT(*) counts the number of employees in each group.

Important: The SELECT list must include either columns specified in GROUP BY or the results of aggregate functions.