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
...               | ...

      

**Note:** The example outputs assume the existence of a `Customers` table with `CustomerID` and `Country` columns. The `...` represents additional rows that would appear in a real-world dataset. The exact numbers and order will depend on the data in your `Customers` table.