Junior
What are grouping queries in SQL?
sobes.tech AI
Answer from AI
Grouping queries in SQL are used to aggregate data based on one or more columns.
Main operators and functions for grouping:
GROUP BY: Divides rows into groups based on the values of specified columns.- Aggregate functions: Perform calculations on groups of rows.
COUNT(): Counts the number of rows in a group.SUM(): Sums the values in a column.AVG(): Calculates the average value.MIN(): Finds the minimum value.MAX(): Finds the maximum value.
HAVING: Filters groups after aggregation and applyingGROUP BY, similar toWHEREfor individual rows.
Example of using GROUP BY and the aggregate function COUNT():
SELECT column1, COUNT(*) -- Selects the column for grouping and the number of rows in the group
FROM table_name
GROUP BY column1; -- Groups by the values of column1
Example of using HAVING:
SELECT column1, COUNT(*)
FROM table_name
GROUP BY column1
HAVING COUNT(*) > 10; -- Selects only groups where the number of rows is greater than 10
Comparison table of WHERE and HAVING:
| Aspect | WHERE | HAVING |
|---|---|---|
| Purpose | Filters individual rows before GROUP BY |
Filters groups of rows after GROUP BY |
| Applies to | Table columns | Results of aggregate functions |
| Order | Executed before GROUP BY |
Executed after GROUP BY and aggregation |