MySQL Aggregation and Window Functions Cheatsheet

group by, having, count, sum, avg, row_number, lag, running totals, and analytical query patterns in MySQL.

View
StandardDetailedCompact
Export
Copy the compact sheet, download it, or print it.
Download
`D` dense toggle · `C` copy all

aggregation and grouping

Summaries, counts, totals, averages, and grouped reporting queries.

Count all rows

Return the total number of rows in a table.

sqlANYcountaggregate
sql
SELECT COUNT(*) AS total_users FROM users;

A basic but essential query for dashboards and sanity checks.

Group rows and count them

Count orders by status.

sqlANYgroup-bycountstatus
sql
SELECT status, COUNT(*) AS total
FROM orders
GROUP BY status
ORDER BY total DESC;

A common reporting pattern for order states, ticket states, and similar grouped data.

Use SUM and AVG

Calculate totals and averages.

sqlANYsumavgrevenue
sql
SELECT SUM(total_amount) AS gross_revenue, AVG(total_amount) AS avg_order_value
FROM orders
WHERE status = 'paid';

Numeric aggregates are core to finance and analytics queries.

Filter grouped results with HAVING

Keep only groups that meet aggregate criteria.

sqlANYhavinggroup-by
sql
SELECT user_id, COUNT(*) AS order_count
FROM orders
GROUP BY user_id
HAVING COUNT(*) >= 5;

`HAVING` filters after aggregation, unlike `WHERE`.

window functions

Ranking, running totals, and partition-aware analytics.

Assign row numbers within each user

Rank a user's orders by recency.

sqlANYwindowrow_numberpartition
sql
SELECT
  user_id,
  id AS order_id,
  created_at,
  ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY created_at DESC) AS rn
FROM orders;

Helpful for picking latest rows per entity.

Calculate a running total

Compute cumulative revenue by day.

sqlANYwindowrunning-total
sql
SELECT
  order_date,
  daily_revenue,
  SUM(daily_revenue) OVER (ORDER BY order_date) AS running_revenue
FROM daily_order_metrics;

Window functions let you keep row-level detail while adding cumulative calculations.

Compare to the previous row with LAG

Calculate day-over-day change.

sqlANYwindowlaganalytics
sql
SELECT
  order_date,
  daily_revenue,
  daily_revenue - LAG(daily_revenue) OVER (ORDER BY order_date) AS delta
FROM daily_order_metrics;

`LAG` is excellent for trend analysis and time-series deltas.

Dense rank grouped totals

Rank categories by revenue without gaps.

sqlANYwindowdense_rank
sql
SELECT
  category,
  revenue,
  DENSE_RANK() OVER (ORDER BY revenue DESC) AS revenue_rank
FROM category_revenue;

Unlike `RANK`, `DENSE_RANK` does not skip numbers after ties.

Recommended next

No recommendations yet.