Aggregate Functions
Aggregate Functions
Section titled βAggregate FunctionsβWhat it means
Section titled βWhat it meansβAggregate functions compute a single result value from a set of rows β SUM, AVG, COUNT, MIN, MAX. Used alone, they collapse an entire result set into one row; combined with GROUP BY, they compute one result per group instead.
Examples
Section titled βExamplesβSELECT COUNT(*) AS total_orders FROM Orders;
SELECT SUM(Amount) AS total_revenue, AVG(Amount) AS avg_order FROM Orders;
SELECT MIN(OrderDate) AS first_order, MAX(OrderDate) AS last_order FROM Orders;
-- Combined with GROUP BY: one result per customer instead of one overallSELECT CustomerId, COUNT(*) AS order_count, SUM(Amount) AS total_spentFROM OrdersGROUP BY CustomerId;Common mistake
Section titled βCommon mistakeβMixing aggregate and non-aggregate columns in the same SELECT without a GROUP BY β SQL Server rejects this, since it canβt determine which individual rowβs value to show alongside a value computed across many rows.
-- Error: Column 'Orders.CustomerId' is invalid in the select list because it-- is not contained in either an aggregate function or the GROUP BY clause.SELECT CustomerId, SUM(Amount) FROM Orders;
-- Fix: add GROUP BY for every non-aggregated columnSELECT CustomerId, SUM(Amount) FROM Orders GROUP BY CustomerId;Quick practice
Section titled βQuick practiceβ-
What does
COUNT(*)return?Answer
The number of rows in the result set, including rows with NULL values in any column. -
Why canβt you select a plain column alongside
SUM(Amount)without also grouping by it?Answer
BecauseSUM(Amount)collapses many rows into one value, but a plain column reference would need to pick a value from one specific row β SQL Server has no way to decide which, so it requires you to either aggregate it too or include it inGROUP BY. -
Does
COUNT(ColumnName)count NULL values in that column?Answer
No βCOUNT(ColumnName)only counts rows where that specific column is non-NULL, unlikeCOUNT(*).