Combining Multiple Aggregate Functions
You'll learn how to request several summary statistics in a single query to build comprehensive data snapshots.
The Core Idea
Rather than running separate queries to get the count, average, minimum, and maximum of your data, SQL lets you combine multiple aggregate functions in one SELECT statement. Think of it like a dashboard—instead of checking five different gauges separately, you see all key metrics at once.
When you list multiple aggregate functions separated by commas, SQL calculates each one independently and returns them as separate columns in your result. This is incredibly efficient for generating summary reports.
How It Works in Practice
Imagine you're analyzing sales data and need a complete picture. Here's how you'd combine aggregates:
SELECT
COUNT(*) AS total_sales,
SUM(amount) AS total_revenue,
AVG(amount) AS average_sale,
MIN(amount) AS smallest_sale,
MAX(amount) AS largest_sale
FROM sales;
This single query gives you five crucial metrics in one result row. You're counting all transactions, summing revenue, finding the average transaction size, and identifying the extreme values—all at once.
You can also mix different columns:
SELECT
COUNT(customer_id) AS customer_count,
AVG(price) AS avg_price,
MAX(quantity) AS max_quantity_ordered
FROM orders;
Why This Matters
Combining aggregates saves time and database resources. Instead of hitting the database five times, you scan the data once and compute everything together. It's like making one trip to the store with a complete shopping list rather than five separate trips.
Key Takeaway: You can combine any number of aggregate functions (COUNT, SUM, AVG, MIN, MAX) in a single SELECT statement to generate comprehensive summary reports efficiently—just separate them with commas and use aliases for clarity.