Sub topic 1
Summarizing a Table with Aggregate Functions
Aggregate functions calculate one value from several rows. They answer questions such as “How many orders exist?” or “What is the total order value?”
This chapter assumes you know basic SELECT, FROM, WHERE, and ORDER BY syntax. It also assumes that orders contains an amount column with numeric values.
Prerequisites
You should understand:
- Tables, rows, and columns.
- Basic
SELECTqueries. NULLas a missing or unknown value.- Numeric and text data types.
The main aggregate functions
SQL provides several common aggregate functions:
| Function | Result |
|---|---|
| `COUNT` | Number of rows or non-`NULL` values |
| `SUM` | Total of numeric values |
| `AVG` | Average of numeric values |
| `MIN` | Smallest value |
| `MAX` | Largest value |
Without GROUP BY, the database treats the entire input as one group and returns one summary row.
SELECT COUNT(*) AS order_count,
SUM(amount) AS total_amount,
AVG(amount) AS average_amount,
MIN(amount) AS smallest_amount,
MAX(amount) AS largest_amount
FROM orders;The AS clauses give the result columns readable names. For example, SUM(amount) adds the values in amount, while AVG(amount) calculates their arithmetic mean.
If the table contains 250 orders, this query still returns one row. The row might contain the count 250, the total amount, the average amount, and the smallest and largest amounts.
How one aggregate works
Consider a table with these order amounts:
| order_id | amount |
|---|---|
| 101 | 20.00 |
| 102 | 35.00 |
| 103 | 45.00 |
The expressions produce these results:
COUNT(*)returns3.SUM(amount)returns100.00.AVG(amount)returns approximately33.33.MIN(amount)returns20.00.MAX(amount)returns45.00.
An aggregate does not preserve the individual rows. It replaces many input rows with one result row.
Choosing the right aggregate
Use COUNT(*) when you need the number of input rows. Use SUM for totals, AVG for typical numeric values, and MIN or MAX for boundaries.
Be careful with averages. An average describes the values included in the calculation, not necessarily every row in the table. Aggregate functions generally ignore NULL values in the column they process. The details of NULL handling, especially for COUNT, are covered in the next sections of this tutorial.
An aggregate can also be combined with WHERE. The filter runs before the aggregate, so only matching rows contribute to the result.
SELECT COUNT(*) AS paid_order_count,
SUM(amount) AS paid_total
FROM orders
WHERE status = 'paid';This query returns one row containing summaries of paid orders only. If no rows match, COUNT(*) returns 0; other aggregates commonly return NULL because there is no value to summarize.
Exercise
Which query returns the largest amount among paid orders?
Show answer
SELECT MAX(amount) AS largestpaidamount FROM orders WHERE status = 'paid';