Country or region and language

    Choose your country or region and your language.

    Suggested for you

      All countries and regions

        Choose your character

        It shows in the top bar and on your profile. Change it any time.

        Sign in or join

        SQL aggregate functions with examples

        Learn SQL aggregate functions with a runnable PostgreSQL example. Use COUNT, SUM, AVG, MIN, and MAX, handle NULLs, and check grouped averages step by step.

        A person practicing on a laptop in a quiet workspace

        SQL aggregate functions summarize multiple rows: COUNT counts, SUM adds values, AVG calculates an arithmetic mean, MIN finds the smallest value, and MAX finds the largest. Without GROUP BY, an aggregate query summarizes the selected rows together; with GROUP BY, it returns a summary for each group. You'll use PostgreSQL to build a department sales summary, check how missing amounts affect averages, and filter the results.

        The five common aggregate functions

        The five common aggregate functions turn a set of input rows into counts, totals, averages, or extreme values. An aggregate calculates across rows, while a scalar function calculates a value for each row, such as converting each department name to lowercase.

        • COUNT counts rows or nonmissing values, depending on its argument.
        • SUM adds the nonmissing values in a numeric column.
        • AVG divides the total of the nonmissing values by their count.
        • MIN returns the smallest nonmissing value.
        • MAX returns the largest nonmissing value.

        In PostgreSQL, NULL represents a missing or unknown value. It isn't zero. Counting all rows includes records with missing amounts, but counting the amount column includes only records with an amount. SUM, AVG, MIN, and MAX also ignore missing amounts.

        Before writing a summary, decide what one input row represents and what one output row should represent. In the example below, each input row represents one sale, and each output row represents one department.

        A sales summary you can run

        A department sales summary needs a grouping column and aggregate calculations for each department. Open a PostgreSQL query editor and run the complete query below unchanged.

        The WITH clause names a temporary query result called sales; it doesn't create a stored table. VALUES supplies the fictional records. The numeric casts make the amount column an exact decimal type, and AS gives each output column a readable name.

        -- Fictional exercise specification
        -- Goal: summarize every department, retaining missing amounts.
        -- Starting records: North has 10.00, 20.00, and NULL;
        -- South has 90.00. Each record represents one sale.
        -- Run unchanged before making any edits.
        WITH sales (department, amount) AS (
          VALUES
            ('North', 10.00::numeric),
            ('North', 20.00::numeric),
            ('North', NULL::numeric),
            ('South', 90.00::numeric)
        )
        SELECT department,
               COUNT(*) AS sale_rows,
               COUNT(amount) AS known_amounts,
               SUM(amount) AS total_amount,
               ROUND(AVG(amount), 2) AS average_amount,
               MIN(amount) AS smallest_amount,
               MAX(amount) AS largest_amount
        FROM sales
        GROUP BY department
        ORDER BY department;
        
        -- Expected rows:
        -- department | sale_rows | known_amounts | total_amount | average_amount | smallest_amount | largest_amount
        -- North      | 3         | 2             | 30.00        | 15.00          | 10.00           | 20.00
        -- South      | 1         | 1             | 90.00        | 90.00          | 90.00           | 90.00
        -- Model calculations:
        -- North: (10 + 20) / 2 = 15; South: 90 / 1 = 90.
        -- Overall known-amount average: (30 + 90) / (2 + 1) = 40.
        -- Average of department averages: (15 + 90) / 2 = 52.5.
        -- These averages answer different questions.

        Read North's result from left to right. North has three sale rows but only two known amounts. Its total is 30.00, and its average is 15.00 because the missing amount doesn't enter either the total or the count used by AVG.

        GROUP BY makes each department a separate group. ORDER BY makes the displayed department order predictable; grouping alone doesn't guarantee result order. ROUND displays the average to two decimal places without changing the starting amounts.

        Once you've matched both output rows, try COUNT, SUM, AVG, MIN and MAX at The Work Gym before moving to the average check.

        The average denominator check

        The denominator check confirms which count belongs under an average's total. The denominator is the number used as the divisor, and for an average per known sale amount, that number is the count of known amounts, not the count of all rows.

        North and South have different numbers of known amounts. Averaging their department averages gives each department equal weight, even though North contributes more known sale amounts. That calculation isn't the overall average per known sale.

        To verify the overall average, replace the summary query with the following standalone PostgreSQL query. Keep all four starting records unchanged. The query combines department totals and known-amount counts, then compares that result with an equally weighted average of department averages.

        -- Verification: keep the original four sales unchanged.
        -- Target: compare an average per known sale with an
        -- equally weighted average of departments.
        WITH sales (department, amount) AS (
          VALUES
            ('North', 10.00::numeric),
            ('North', 20.00::numeric),
            ('North', NULL::numeric),
            ('South', 90.00::numeric)
        ), department_totals AS (
          SELECT department,
                 SUM(amount) AS total_amount,
                 COUNT(amount) AS known_amounts,
                 AVG(amount) AS department_average
          FROM sales
          GROUP BY department
        )
        SELECT ROUND(
                 SUM(total_amount) / NULLIF(SUM(known_amounts), 0), 2
               ) AS overall_average,
               ROUND(AVG(department_average), 2) AS unweighted_average
        FROM department_totals;
        
        -- Model calculations:
        -- Overall: (30 + 90) / (2 + 1) = 40.
        -- Unweighted: (15 + 90) / 2 = 52.5.
        -- Expected row:
        -- overall_average | unweighted_average
        -- 40.00           | 52.50

        NULLIF returns NULL when its two arguments are equal. Here, NULLIF protects the division when the combined known-amount count is zero. An unknown average is more accurate than pretending the average is zero.

        Use the combined total and count when your question is about the average per known sale. Use an unweighted department average only when equal department weighting is intentional. The verification query also keeps department averages unrounded until the final display, avoiding errors from combining rounded values.

        Row filters and group filters

        WHERE filters individual records before aggregation, while HAVING filters groups after aggregation. Use WHERE for a condition on each sale and HAVING for a condition on a department's calculated total.

        For the variation, replace the previous query with the standalone query below. Keep the starting records unchanged, add the sale-amount condition before GROUP BY, and add the department-total condition after GROUP BY. The new request is to include only sales of at least 20.00, then retain departments whose included sales total at least 50.00.

        -- Fictional variation specification
        -- Target: include sales of at least 20.00, then retain
        -- departments with included sales totaling at least 50.00.
        -- Starting records remain North: 10.00, 20.00, NULL;
        -- South: 90.00.
        -- Changes: add WHERE before GROUP BY and HAVING after it;
        -- select the qualifying row count and total.
        WITH sales (department, amount) AS (
          VALUES
            ('North', 10.00::numeric),
            ('North', 20.00::numeric),
            ('North', NULL::numeric),
            ('South', 90.00::numeric)
        )
        SELECT department,
               COUNT(*) AS qualifying_sales,
               SUM(amount) AS total_amount
        FROM sales
        WHERE amount >= 20
        GROUP BY department
        HAVING SUM(amount) >= 50
        ORDER BY department;
        
        -- Model calculations:
        -- WHERE removes North's 10.00 and NULL records.
        -- Remaining totals: North = 20.00; South = 90.00.
        -- HAVING removes North because 20.00 is below 50.00.
        -- Expected row:
        -- department | qualifying_sales | total_amount
        -- South      | 1                | 90.00

        The row threshold determines which sales contribute to the summary. The department threshold then tests the totals calculated from those remaining sales. North doesn't qualify because its included total is only 20.00.

        A comparison with NULL doesn't evaluate to true, so North's missing amount doesn't pass the WHERE condition. In the variation, the row count therefore counts only qualifying sales, not every original sale.

        Common mistakes and further practice

        Most summary mistakes come from counting the wrong records, grouping at the wrong level, or filtering at the wrong stage. Check those choices before changing the aggregate function.

        • An aggregate filter in WHERE produces an error in these queries. Put the department-total condition in HAVING, where the group total is available.
        • Selecting department without grouping by department produces an error in these queries. Every selected value must have a clear meaning for each output group.
        • DISTINCT isn't a repair for an incorrectly defined group. Decide what each output row represents, then set GROUP BY accordingly.
        • An overall average of 52.50 signals equal department weighting in this example. Use combined totals and known-amount counts for the average per known sale.

        One limitation matters when you use real workplace data: correct aggregate syntax can't detect sales duplicated by a join, which combines records from different tables. The example assumes one input row per sale and doesn't cover join validation.

        Common questions

        What are the five common aggregate functions in SQL? The five common aggregate functions are COUNT, SUM, AVG, MIN, and MAX. They calculate counts, totals, arithmetic means, smallest values, and largest values across rows.

        Is COUNT(*) an aggregate function? Yes, COUNT with an asterisk argument is an aggregate function that counts rows, including rows containing NULL values. With GROUP BY, it counts the rows within each group.

        How do SQL aggregate functions handle NULL values? In PostgreSQL, SUM, AVG, MIN, MAX, and COUNT with a column argument ignore NULL values in that column. Counting all rows still includes rows with missing values. If there are no nonmissing inputs, COUNT returns zero, while SUM, AVG, MIN, and MAX return NULL.

        What's the difference between WHERE and HAVING? WHERE filters input rows before grouping and aggregation. HAVING filters the groups after their aggregate values have been calculated, so it can test a department's total.

        Why can averaging group averages give the wrong result? Averaging group averages gives every group equal weight, even when groups contain different numbers of known values. In the sales example, equal department weighting gives 52.50, while the overall average per known sale is 40.00. Combine totals and their corresponding counts when you need the overall average per known value.

        Practice what this post teaches

        After reproducing the results, use Practice: summarize data to practice without copying the solution. The Work Gym checks exercises automatically and gives a hint that names the mistake.

        Practice what this post teaches

        Your Work Gym account

        Save your progress and pick up on another device. Your browser's progress comes with you.

        Your account can start a 5-day free trial: every course, unit, project and exam. Card needed; cancel any time and pay nothing.

        New accounts get 6 hours of full access: every course, unit, project and exam. The clock starts when you go past the free lessons.

        Plan your practice from a job ad or syllabus

        Have a referral code?

        or

        You can keep practicing without an account.

        Help and feedback

        Ask a question, tell us what is not working, or share an idea. We reply by email.

        What is it about?

        We use it only to reply to you.