Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 21/ 160
02. Aggregations, Functions & Data Manipulation

Aggregate Functions (COUNT, SUM, AVG, MIN, MAX)

Collapse many rows into summary metrics with the core aggregate functions.

BeginnerCOUNT / SUM · AVG3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

They squeeze a pile of rows into one number: how many, the total, the average, the smallest or the biggest.

Think of it like…

Closing the till at a shop: count the receipts (COUNT), add up the takings (SUM), work out the average sale (AVG), and note the smallest and biggest sale (MIN, MAX).

Where you’ve seen it

SELECT COUNT(*) AS orders, SUM(amount) AS revenue, AVG(amount) AS avg_order, MIN(created_at) AS first_order, MAX(created_at) AS last_order FROM orders WHERE created_at >= '2026-11-01'; gives a month-to-date summary in one row.

Words you’ll hear

Aggregate
A function that reduces a set of rows to one value.
NULL handling
SUM, AVG, MIN, MAX and COUNT(col) skip NULLs; COUNT(*) counts every row.
Empty input
COUNT returns 0; SUM, AVG, MIN and MAX return NULL.
Average of averages
Averaging per-group averages, which usually isn't the overall average.

Visual diagram

Loading interactive diagram

Theory & example queries

How each one treats NULLs and empty input

SUM, AVG, MIN and MAX look only at non-NULL values, so AVG divides by the number of non-NULL values, not by the number of rows. If missing should mean zero, say so explicitly with AVG(COALESCE(x, 0)).

Over zero rows (or only NULLs), COUNT returns 0 but the others return NULL, which shows up as blank cells or breaks arithmetic in reports. Wrap totals you display: COALESCE(SUM(amount), 0).

A safe total for a day with no ordersQuery example
1Input dataStart from the source rows or state that the statement sees.
orders
3 rows
orders sample rows
idcustomer_idstatusamountcoupon_code
1011paid249NULL
1022paid120WELCOME10
1031shipped89.5NULL
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  COALESCE(SUM(amount), 0) AS revenue3FROM4  orders5WHERE6  created_at::date = '2026-12-25';
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/6
3OutputInspect the representative rows, affected-row count, plan, or command status.
Expected output1 sample row
Expected output
revenue
0

Note: No orders matched the date, so SUM returned NULL and COALESCE converted it to 0 for the report.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Key takeaway: Only COUNT(*) sees NULLs; only COUNT returns 0 on no rows.

Types, DISTINCT and the average-of-averages trap

Result types differ by database. In SQL Server, AVG over an integer column returns an integer, so the average of 1 and 2 is 1; cast first, as in AVG(CAST(x AS decimal(10,2))). PostgreSQL and MySQL return a decimal. MIN and MAX work on any sortable type: dates, timestamps and text.

Averaging pre-computed averages weights every group equally, however many rows it has. The average order value across all orders is SUM(amount) / COUNT(*) over the orders, not the mean of each day's average. Aggregates also accept DISTINCT (COUNT(DISTINCT user_id)), though SUM(DISTINCT) is rarely what you want.

Correct overall average from daily totalsQuery example
1Input dataStart from the source rows or state that the statement sees.
daily_stats
2 rows
daily_stats sample rows
dayrevenueorders
2026-11-201001
2026-11-216003
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  SUM(revenue) / SUM(orders) AS avg_order_value3FROM4  daily_stats;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/4
3OutputInspect the representative rows, affected-row count, plan, or command status.
Expected output1 sample row
Expected output
avg_order_value
175

Note: For sample daily totals of revenue 100 / 1 order and revenue 600 / 3 orders, (100 + 600) / (1 + 3) = 175.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

rather than AVG(avg_order_value).

Key takeaway: Combine sums and counts, not averages.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1WHERE

Choose the rows

Filter to the rows the metric should cover (this month, paid orders) before aggregating.

SQL at this step
1WHERE2  status = 'paid'3  AND created_at >= '2026-11-01'
What to watch at this step
Filter
before aggregating
Tip: use ← → to move between steps

When to use it & trade-offs

What it is

Aggregate functions turn many rows into one value: COUNT (how many), SUM (total), AVG (mean), MIN and MAX (smallest and largest). Without GROUP BY they summarise the whole result as one row; with GROUP BY they summarise each group. All of them except COUNT(*) ignore NULLs.

Why it matters: Every metric on a dashboard is an aggregate, and small details change the numbers: NULLs skipped by AVG, NULL instead of 0 from SUM on no rows, or integer averages that silently drop decimals. Getting these right is the difference between a report people trust and one they double-check.

When to reach for it

  • KPIs: total revenue, order count, average order value
  • First and last activity dates with MIN and MAX
  • Per-group metrics together with GROUP BY

When to avoid or be careful

  • Averaging averages to get an overall figure
  • Showing SUM results without COALESCE where empty periods are possible
  • Integer AVG in SQL Server without casting

Plain aggregates vs GROUP BY vs window aggregates

Aggregate without GROUP BY
Best for: One summary row for the whole filtered set

Strengths: Simplest overall totals and KPIs.

Watch out: No breakdown by dimension.

Aggregate with GROUP BY
Best for: Metrics per group

Strengths: One row per group with any aggregates.

Watch out: Detail rows are collapsed.

Aggregate as a window (OVER)
Best for: Each row next to its group's total or average

Strengths: Keeps detail rows.

Watch out: Doesn't reduce the number of rows.

Interview signals & numbers to know

When this topic comes up

  • “Total / average / count of …”
  • “First and last order date per customer”
  • Blank cells in a report for days with no data
  • “The average looks wrong”
  • Weighted average

Benchmarks & rules of thumb

0 -
COUNT over no rows
NULL -
SUM / AVG / MIN / MAX over no rows
1 -
row returned without GROUP BY

Common mistakes & follow-ups

Common interview mistakes

  • Assuming AVG counts NULL rows as zero; it skips them.
  • Displaying SUM directly, so days with no orders show NULL instead of 0.
  • Reporting the average of daily averages as the overall average order value.

Likely interviewer follow-ups

  • What do SUM and COUNT return when no rows match?
  • How does AVG treat NULL values, and how would you treat them as zero?
  • Why is the average of daily averages usually different from the overall average?
Interview tip: Mention NULL and empty-set behaviour whenever you use aggregates in an answer. It's a small addition that shows you think about edge cases.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Aggregate Functions (COUNT, SUM, AVG, MIN, MAX) with hands-on SQL practice and interview Q&A.

Open SQL Practice →SQL interview Q&A
Previous topic
SQL Execution Order vs Logical Writing Order
Next topic
COUNT(*) vs COUNT(column) vs COUNT(DISTINCT column)