Mastering MySQL for Data AnalystsLesson 15 of 42
Lesson 15 of 42

Aggregate Functions: SUM, AVG, COUNT, MIN, MAX & GROUP_CONCAT in MySQL

Overview & Learning Objectives

Data analysis begins with summarizing thousands of atomic records into meaningful business KPIs: total sales volume, average order value, unique customers, and category boundaries. MySQL provides core ANSI aggregate functions (`COUNT`, `SUM`, `AVG`, `MIN`, `MAX`) which collapse rows into scalar summaries while automatically ignoring NULL values. In addition, MySQL features the unique `GROUP_CONCAT()` function, allowing analysts to aggregate rows into readable comma-separated lists.

  • Master the critical distinctions between `COUNT(*)`, `COUNT(col)`, and `COUNT(DISTINCT col)`.
  • Compute executive revenue and average ticket metrics using `SUM()` and `AVG()`.
  • Leverage MySQL's signature `GROUP_CONCAT()` to aggregate string values with custom sorting and delimiters.

Industry Standard

Standard: Analytics engineering teams at Swiggy and Zomato standardize financial reporting on `COUNT(DISTINCT user_id)` and `ROUND(AVG(bill_amount), 2)` to monitor daily customer retention and basket health.

Real-World Example: ScoopCraft Dark-Store Daily KPI Rollup

ScoopCraft operations computes daily summary metrics across 15,000 order transactions.

Metric NameSQL ExpressionResultAnalytical Insight
Total OrdersCOUNT(*)15,420 ordersTotal delivery volume across all hubs
Unique BuyersCOUNT(DISTINCT customer_id)11,200 customersMeasures customer breadth vs repeat orders
Gross SalesSUM(order_total)₹5,240,000.00Total top-line daily gross merchandise value
Average TicketROUND(AVG(order_total), 2)₹339.82Average consumer spend per order

Functions & Syntax Covered in this Chapter

Here is the definition, execution syntax, parameter breakdown, and real-world business example for each function/syntax covered in this chapter:

Feature 1

COUNT() / COUNT(DISTINCT)

Definition: Counts rows matching criteria. COUNT(*) counts all rows including NULLs; COUNT(col) counts non-NULL values; COUNT(DISTINCT col) counts unique values.

Syntax / Code Pattern:
SELECT COUNT(*), COUNT(DISTINCT customer_id) FROM orders;
Parameters Breakdown:
  • *: Counts every row satisfying the WHERE clause.
  • DISTINCT col: Deduplicates values before counting, ignoring NULLs.
Real-World Example (Total vs Unique Customer Orders):
Problem / Scenario: Count total orders and total unique customers who purchased today.
SQL Query / Expression: COUNT(order_id) AS total_orders, COUNT(DISTINCT customer_id) AS unique_buyers
Result: total_orders: 1,420, unique_buyers: 980
Why it works: Counts order rows and deduplicates repeating customer IDs.
Feature 2

SUM() & AVG()

Definition: Calculates the arithmetic sum or average of a numeric column, automatically skipping NULL records.

Syntax / Code Pattern:
SELECT SUM(order_total), ROUND(AVG(order_total), 2) FROM orders;
Parameters Breakdown:
  • col: Numeric column (INT, DECIMAL, FLOAT).
Real-World Example (Revenue & Average Order Value (AOV)):
Problem / Scenario: Calculate gross sales revenue and average basket size for the Indiranagar store.
SQL Query / Expression: SUM(order_total) AS gross_rev, AVG(order_total) AS aov
Result: gross_rev: ₹45,200.00, aov: ₹318.31
Why it works: Sums all order totals and divides by non-null row count.
Feature 3

MIN() & MAX()

Definition: Returns the minimum or maximum value in a set. Works on numeric, text (alphabetical), and temporal (oldest/newest date) columns.

Syntax / Code Pattern:
SELECT MIN(order_date), MAX(order_date), MIN(price), MAX(price) FROM products;
Parameters Breakdown:
  • col: Any comparable column type.
Real-World Example (Price Range Analysis):
Problem / Scenario: Find the lowest and highest priced ice cream tub in the catalog.
SQL Query / Expression: MIN(price) AS cheapest, MAX(price) AS most_expensive
Result: cheapest: ₹90.00, most_expensive: ₹550.00
Why it works: Scans the price index to identify extreme boundary values.
Feature 4

GROUP_CONCAT() (MySQL Signature Aggregate)

Definition: Concatenates non-NULL values from multiple rows into a single comma-separated string per group with optional sorting and separators.

Syntax / Code Pattern:
SELECT store_id, GROUP_CONCAT(flavor_name ORDER BY price DESC SEPARATOR " | ") FROM menu GROUP BY store_id;
Parameters Breakdown:
  • DISTINCT: Optional flag eliminating duplicate string values.
  • ORDER BY: Specifies ordering of elements within the concatenated result.
  • SEPARATOR: String literal inserted between values (defaults to comma ",").
Real-World Example (Store Product Catalog Listing):
Problem / Scenario: List all flavors available at each dark-store as a single readable line.
SQL Query / Expression: GROUP_CONCAT(flavor_name SEPARATOR ', ')
Result: 'Belgian Chocolate, Alphonso Mango, Roasted Almond'
Why it works: Aggregates multiple child rows into a single scalar string representation.

Common Mistakes & Limitations

  • Assuming `AVG(tip_amount)` includes orders with NULL tips; `AVG()` ignores NULLs, calculating the average tip only among customers who tipped.
  • Exceeding MySQL's default `group_concat_max_len` (1024 bytes) when using `GROUP_CONCAT()` on large datasets, causing truncated strings.

Keyboard Shortcuts (MySQL Workbench)

ActionWindowsMac
Execute SQL QueryCtrl + EnterCmd + Enter

Pro Tips & Modern Best Practices

  • If you need `GROUP_CONCAT()` to output long strings without truncation, execute `SET SESSION group_concat_max_len = 1000000;` before running your query.
  • Use `SUM(order_status = "Delivered")` in MySQL as a brilliant shorthand for conditional counting (since boolean expressions evaluate to 1 or 0!).