SELECT
MIN(price) AS lowest_price
FROM products;
1️⃣1️⃣ MAX()
MAX() finds the largest value.SELECT
MAX(salary) AS highest_salary
FROM employees;
SELECT
MAX(amount) AS largest_order
FROM orders;
1️⃣2️⃣ Using Multiple Aggregate Functions
You can use several aggregate functions in the same query.
SELECT
COUNT(*) AS total_orders,
SUM(amount) AS total_revenue,
AVG(amount) AS average_order_value,
MIN(amount) AS smallest_order,
MAX(amount) AS largest_order
FROM orders;
This single query gives you a basic sales summary.
1️⃣3️⃣ Aggregate Functions With WHERE
Example:
Analyze completed orders only.
SELECT
COUNT(*) AS completed_orders,
SUM(amount) AS revenue,
AVG(amount) AS average_order_value,
MIN(amount) AS smallest_order,
MAX(amount) AS largest_order
FROM orders
WHERE order_status = 'Completed';
This is a powerful analytical pattern.
1️⃣4️⃣ NULL and SUM()
SUM() generally ignores NULL values.Suppose:
amount 1000, 2000, NULL, 3000
Then: SUM(amount) = 6000
However, if all values are NULL, the result can be NULL rather than 0.
You can handle that later using
COALESCE().Example:
SELECT
COALESCE(SUM(amount), 0) AS total_revenue
FROM orders
WHERE order_status = 'Completed';
1️⃣5️⃣ Aggregate Functions Are the Foundation of KPIs
Most business dashboards are built using aggregate functions.
For example:
• Revenue =
SUM(amount)• Number of Orders =
COUNT(*)• Customers =
COUNT(DISTINCT customer_id)• Average Order Value =
AVG(amount)• Largest Order =
MAX(amount)This is why mastering aggregates is critical.
1️⃣6️⃣ Calculating Average Order Value
A common e-commerce KPI is AOV — Average Order Value.
A simple version:
SELECT
AVG(amount) AS average_order_value
FROM orders
WHERE order_status = 'Completed';
Another formulation is:
SELECT
SUM(amount) / COUNT(*) AS average_order_value
FROM orders
WHERE order_status = 'Completed';
The
AVG() version is usually clearer when each row represents one order.1️⃣7️⃣ Calculating Revenue Per Customer
Suppose the business asks:
What is the average revenue generated per unique customer?
You need to be careful not to divide revenue by the number of orders.
SELECT
SUM(amount) /
COUNT(DISTINCT customer_id) AS revenue_per_customer
FROM orders
WHERE order_status = 'Completed';
This is a good example of translating a business metric into SQL.
1️⃣8️⃣ Aggregate Functions + Expressions
You can aggregate calculations.
Example:
SELECT
SUM(quantity * unit_price) AS total_sales
FROM order_items;
SQL first evaluates:
quantity * unit_price for each row, then sums those values.1️⃣9️⃣ Aggregate Functions + CASE
You can create conditional metrics.
Example:
SELECT
COUNT(*) AS total_orders,
SUM(
CASE
WHEN order_status = 'Completed'
THEN 1
ELSE 0
END
) AS completed_orders
FROM orders;
This technique becomes extremely important when building dashboards.
2️⃣0️⃣ Example: Success Rate
Suppose you have payment transactions. You want:
Percentage of successful transactions.