SQL GROUP BY Keyword
The GROUP BY
clause in SQL groups rows that have the same values in specified columns into summary rows, like creating a summary table.
GROUP BY: Definition and Usage
GROUP BY
is typically used with aggregate functions (like COUNT()
, SUM()
, AVG()
, MAX()
, MIN()
) to perform calculations on grouped data. It's a powerful tool for summarizing and analyzing data.
Syntax
Syntax
SELECT aggregate_function(column_name), ...
FROM table_name
GROUP BY column_name
ORDER BY aggregate_function(column_name) [ASC|DESC];
Examples
Grouping Customers by Country
This query counts the number of customers in each country.
Syntax
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country;
Output
COUNT(CustomerID) | Country
-------------------------
2 | Mexico (Example output - adapt to your data)
1 | UK
3 | USA
... | ...
Grouping and Sorting Customers by Country
This query groups customers by country and then sorts the results to show the countries with the most customers first.
Syntax
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
ORDER BY COUNT(CustomerID) DESC;
Output
COUNT(CustomerID) | Country
-------------------------
3 | USA (Example output - adapt to your data)
2 | Mexico
1 | UK
... | ...