The Money Metrics: SUM and AVG
The Financial Question
The CFO walked in. *"What was our total revenue last quarter? And what was the average order value?"*
These are the two numbers that make or break a business presentation. Total Revenue tells شما the scale. Average Order Value (AOV) tells شما the customer quality.
The Quest: The Financial Functions
SQL has two more champion aggregation functions: `SUM()` and `AVG()`.
The Implementation: Calculating the Fortune
The Total
`SUM()` adds up all the values in a column.
-- Total revenue from all orders
SELECT SUM(order_amount) AS total_revenue
FROM orders;
The Average
`AVG()` calculates the mean of all the values.
-- Average order value
SELECT AVG(order_amount) AS avg_order_value
FROM orders;
All Together Now
You can (and should) put multiple aggregations in one query:
SELECT
COUNT(*) AS total_orders,
SUM(order_amount) AS total_revenue,
AVG(order_amount) AS avg_order_value
FROM orders;
The "Oops" Moment
I once ran `SUM()` on a column that contained NULLs in the middle of a migration. The sum was mysteriously lower than expected. Remember, `SUM()` ignores NULLs.
**Pro Tip**: If you suspect missing data, always run `COUNT(column)` alongside `SUM(column)` to see if the row counts match up.
The Victory
The CFO got a three-number summary that told the entire story of the quarter. I had turned a database of 100,000 transactions into a 3-second answer. That's the power of aggregation.
Your Task for Today
Run `SUM()` and `AVG()` on any numerical column. Put them in the same query and watch how SQL returns a single row of "Answers."
*Day 18: The Power of Grouping—GROUP BY.*