LESSON 12 OF 14

Grouping, Aggregate Functions, and HAVING

This lesson explains how to use COUNT, SUM, AVG, MIN, and MAX with GROUP BY to create summaries and HAVING to filter grouped results.

45 dk 126

Introduction

In previous lessons, you learned how to retrieve data with SELECT, filter and sort rows, and combine related tables with JOIN statements. In practical database work, however, you often need more than a list of individual records. You may need to know how many products exist in each category, how much each customer has spent, or what the average order value is for a group of customers.

Aggregate functions and grouping provide the foundation for these summary reports. In this lesson, you will work with COUNT, SUM, AVG, MIN, and MAX. You will also learn how GROUP BY divides rows into groups and how HAVING filters groups after their aggregate values have been calculated.

An aggregate function performs a calculation over a set of rows and returns a single value. When GROUP BY is used, the calculation is performed separately for each group.

Example data model

The examples assume a database named SalesDemo with the following tables:

  • Products(ProductID, ProductName, CategoryName, UnitPrice, StockQuantity)
  • Customers(CustomerID, CustomerName, City)
  • Orders(OrderID, CustomerID, OrderDate, TotalAmount, Status)

Start the practice session by selecting the database:

USE SalesDemo;
GO

Aggregate functions

Counting rows with COUNT

COUNT returns the number of values or rows in a set. To count every row in a table, use COUNT(*):

SELECT COUNT(*) AS ProductCount
FROM Products;

This query returns the total number of rows in Products. To count non-NULL values in a particular column, provide the column name:

SELECT COUNT(UnitPrice) AS ProductsWithPrice
FROM Products;

COUNT(UnitPrice) excludes rows where UnitPrice is NULL. In contrast, COUNT(*) counts rows regardless of NULL values in their columns. To count distinct categories, use COUNT(DISTINCT ...):

SELECT COUNT(DISTINCT CategoryName) AS CategoryCount
FROM Products;

Calculating totals with SUM

SUM adds numeric values in a column. The following query calculates the total quantity currently represented by the product rows:

SELECT SUM(StockQuantity) AS TotalStock
FROM Products;

You can also calculate the total value of completed orders:

SELECT SUM(TotalAmount) AS CompletedOrderAmount
FROM Orders
WHERE Status = 'Completed';

SUM ignores NULL values. If no matching rows exist, the result can be NULL. When an application requires zero instead, use COALESCE:

SELECT COALESCE(SUM(TotalAmount), 0) AS CompletedAmount
FROM Orders
WHERE Status = 'Completed';

Calculating averages with AVG

AVG calculates the arithmetic average of numeric values. To find the average product price:

SELECT AVG(UnitPrice) AS AveragePrice
FROM Products;

AVG ignores NULL values, so products without a price do not participate in the calculation. For a consistent two-decimal display, convert the result to a decimal type:

SELECT CAST(AVG(UnitPrice) AS decimal(10, 2)) AS AveragePrice
FROM Products;

Finding minimum and maximum values

MIN returns the smallest value and MAX returns the largest value:

SELECT
    MIN(UnitPrice) AS LowestPrice,
    MAX(UnitPrice) AS HighestPrice
FROM Products;

These functions can also be used with date and character columns. For example, the following query returns the first and most recent order dates:

SELECT
    MIN(OrderDate) AS FirstOrderDate,
    MAX(OrderDate) AS LastOrderDate
FROM Orders;

Grouping rows with GROUP BY

Without GROUP BY, an aggregate function normally produces one result for the entire input set. GROUP BY divides rows according to shared values and produces one result row for each group.

To count products in each category, write:

SELECT
    CategoryName,
    COUNT(*) AS ProductCount
FROM Products
GROUP BY CategoryName
ORDER BY ProductCount DESC;

CategoryName identifies each group, while COUNT(*) counts the rows inside that group. GROUP BY does not guarantee the order of the result, so use ORDER BY whenever a particular order is required.

You can calculate several summaries in the same grouped query:

SELECT
    CategoryName,
    COUNT(*) AS ProductCount,
    SUM(StockQuantity) AS CategoryStock,
    AVG(UnitPrice) AS AveragePrice,
    MIN(UnitPrice) AS LowestPrice,
    MAX(UnitPrice) AS HighestPrice
FROM Products
GROUP BY CategoryName
ORDER BY CategoryName;

This report displays the number of products, total stock, average price, lowest price, and highest price for every category. To control the numeric type of the average, use CAST or CONVERT:

SELECT
    CategoryName,
    CAST(AVG(UnitPrice) AS decimal(10, 2)) AS AveragePrice
FROM Products
GROUP BY CategoryName;

Grouping by more than one column

A query can group by multiple columns. For example, you can summarize orders by both city and status:

SELECT
    c.City,
    o.Status,
    COUNT(*) AS OrderCount,
    SUM(o.TotalAmount) AS TotalAmount
FROM Orders AS o
INNER JOIN Customers AS c
    ON c.CustomerID = o.CustomerID
GROUP BY c.City, o.Status
ORDER BY c.City, o.Status;

Each combination of city and status is a separate group. For example, “Ankara - Completed” and “Ankara - Pending” are different groups even though they have the same city.

The difference between WHERE and HAVING

The distinction between WHERE and HAVING is essential. WHERE filters individual rows before grouping. HAVING filters groups after grouping and aggregation.

Suppose you want a city-based report containing only completed orders. Use WHERE to remove other rows before the grouping step:

SELECT
    c.City,
    COUNT(*) AS CompletedOrderCount,
    SUM(o.TotalAmount) AS CompletedAmount
FROM Orders AS o
INNER JOIN Customers AS c
    ON c.CustomerID = o.CustomerID
WHERE o.Status = 'Completed'
GROUP BY c.City;

Now suppose you want to show only cities whose order total exceeds 10000. That condition applies to a group, so it belongs in HAVING:

SELECT
    c.City,
    COUNT(*) AS OrderCount,
    SUM(o.TotalAmount) AS TotalAmount
FROM Orders AS o
INNER JOIN Customers AS c
    ON c.CustomerID = o.CustomerID
GROUP BY c.City
HAVING SUM(o.TotalAmount) > 10000
ORDER BY TotalAmount DESC;

HAVING commonly contains an aggregate expression. Although aliases may be accepted in some query contexts, using the aggregate expression directly in HAVING is clearer and avoids ambiguity.

Filtering groups with COUNT

To find customers who have placed at least three orders, group by customer and filter the groups with HAVING:

SELECT
    CustomerID,
    COUNT(*) AS OrderCount,
    SUM(TotalAmount) AS TotalAmount
FROM Orders
GROUP BY CustomerID
HAVING COUNT(*) >= 3
ORDER BY OrderCount DESC;

The COUNT condition filters customer groups, not individual order rows. WHERE and HAVING can be used together when they serve different purposes:

SELECT
    CustomerID,
    COUNT(*) AS CompletedOrderCount,
    SUM(TotalAmount) AS CompletedAmount
FROM Orders
WHERE Status = 'Completed'
GROUP BY CustomerID
HAVING SUM(TotalAmount) >= 5000;

First, only completed orders enter the grouping operation. Then, only customers whose completed-order total is at least 5000 remain in the result.

Important GROUP BY rules

  • A non-aggregated column in the SELECT list generally must also appear in the GROUP BY list.
  • SELECT CategoryName, ProductName, COUNT(*) FROM Products GROUP BY CategoryName is invalid because ProductName is neither grouped nor aggregated.
  • Do not place aggregate conditions in WHERE. Conditions such as SUM(...) > 100 belong in HAVING.
  • GROUP BY does not sort the output. Add ORDER BY when the result must be ordered.
  • NULL values in a grouping column are collected into one group. Use COALESCE if you want to display a label instead of NULL.
  • AVG, SUM, MIN, MAX, and COUNT(column) ignore NULL values. Make sure this behavior matches the reporting requirement.

Step-by-step reporting example

Let us build a category report that combines filtering, grouping, aggregation, group filtering, and sorting.

  1. Keep only products with stock:

    WHERE StockQuantity > 0
  2. Group the remaining rows by category:

    GROUP BY CategoryName
  3. Calculate the required summaries:

    COUNT(*) AS ProductCount,
    SUM(StockQuantity) AS TotalStock,
    AVG(UnitPrice) AS AveragePrice
  4. Keep categories containing at least two products:

    HAVING COUNT(*) >= 2
  5. Sort by total stock in descending order:

    ORDER BY TotalStock DESC;

The complete query is:

SELECT
    CategoryName,
    COUNT(*) AS ProductCount,
    SUM(StockQuantity) AS TotalStock,
    CAST(AVG(UnitPrice) AS decimal(10, 2)) AS AveragePrice,
    MIN(UnitPrice) AS LowestPrice,
    MAX(UnitPrice) AS HighestPrice
FROM Products
WHERE StockQuantity > 0
GROUP BY CategoryName
HAVING COUNT(*) >= 2
ORDER BY TotalStock DESC;

Common mistakes

Using an aggregate function in WHERE

The following query is invalid:

SELECT CategoryName, SUM(StockQuantity)
FROM Products
WHERE SUM(StockQuantity) > 100
GROUP BY CategoryName;

Aggregation occurs as part of the grouping process, so the condition must be moved to HAVING:

SELECT CategoryName, SUM(StockQuantity) AS TotalStock
FROM Products
GROUP BY CategoryName
HAVING SUM(StockQuantity) > 100;

Confusing COUNT(*) and COUNT(column)

If a column can contain NULL values, COUNT(column) does not count those rows. Use COUNT(*) when the requirement is to count rows rather than non-NULL values.

Ignoring row multiplication after a JOIN

A one-to-many JOIN can produce multiple result rows for a single logical business entity. For example, joining order headers to order details creates one row per detail. If you then calculate totals without considering the reporting level, the result may be larger than expected. Decide whether the report describes orders, order lines, customers, or products before choosing the aggregate expression.

Short practice exercise

Create the following report from the Orders table:

  • Return one row for each customer.
  • Count the customer's orders.
  • Calculate the total order amount.
  • Display the average order amount with two decimal places.
  • Return only customers whose total exceeds 3000.
  • Sort by total amount from highest to lowest.

A suitable solution is:

SELECT
    CustomerID,
    COUNT(*) AS OrderCount,
    SUM(TotalAmount) AS TotalAmount,
    CAST(AVG(TotalAmount) AS decimal(10, 2)) AS AverageOrderAmount
FROM Orders
GROUP BY CustomerID
HAVING SUM(TotalAmount) > 3000
ORDER BY TotalAmount DESC;

Conclusion

Aggregate functions transform detailed rows into useful summaries. COUNT returns a count, SUM calculates a total, AVG calculates an average, MIN returns the smallest value, and MAX returns the largest value. GROUP BY applies these calculations separately to each group, while WHERE filters rows before grouping and HAVING filters groups after aggregation.

These techniques are central to operational reports, dashboards, data validation, and application queries. Before writing a grouped query, identify which rows should participate, decide the level of grouping, select the required aggregate calculations, and then define the group-level filter. This planning process produces T-SQL statements that are easier to verify, maintain, and extend.

Sources