SQL Server Interview Question #84

What does AVG() do?

Aggregate Functions, GROUP BY & Window Functions Mid-Level Intermediate

Detailed Explanation

AVG returns the arithmetic average of non-NULL values in an expression. NULL values are ignored rather than treated as zero.

The return type depends on the input type. When exact precision is important, particularly for financial calculations, explicitly using an appropriate DECIMAL type can make the intended precision clear.

Code Example

SELECT CategoryId,
       AVG(CAST(Price AS DECIMAL(18,2))) AS AveragePrice
FROM dbo.Products
GROUP BY CategoryId;