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
Count all rows
SELECT COUNT(*) AS total_users FROM users;

# Return the total number of rows in a table.

Group rows and count them
SELECT status, COUNT(*) AS total
FROM orders
GROUP BY status
ORDER BY total DESC;

# Count orders by status.

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

# Calculate totals and averages.

Filter grouped results with HAVING
SELECT user_id, COUNT(*) AS order_count
FROM orders
GROUP BY user_id
HAVING COUNT(*) >= 5;

# Keep only groups that meet aggregate criteria.

## window functions
Assign row numbers within each user
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;

# Rank a user's orders by recency.

Calculate a running total
SELECT
  order_date,
  daily_revenue,
  SUM(daily_revenue) OVER (ORDER BY order_date) AS running_revenue
FROM daily_order_metrics;

# Compute cumulative revenue by day.

Compare to the previous row with LAG
SELECT
  order_date,
  daily_revenue,
  daily_revenue - LAG(daily_revenue) OVER (ORDER BY order_date) AS delta
FROM daily_order_metrics;

# Calculate day-over-day change.

Dense rank grouped totals
SELECT
  category,
  revenue,
  DENSE_RANK() OVER (ORDER BY revenue DESC) AS revenue_rank
FROM category_revenue;

# Rank categories by revenue without gaps.

Recommended next

No recommendations yet.