PostgreSQL AVG

PostgreSQL AVG() Function

The AVG() function is another critical mathematical aggregate function. It precisely calculates and returns the average value of a numeric column.

Finding averages is essential for analyzing statistical trends over large datasets. Like SUM(), this function strictly operates on numeric data columns only.

How AVG() Calculates

Behind the scenes, the function adds all the valid numbers together entirely. It then neatly divides that gross total by the exact number of valid rows counted.

Crucially, the AVG() function completely ignores NULL values in its calculation. A row with a missing value does not lower the mathematical average incorrectly.

Basic AVG Example:

-- Calculate the average cost of all products listed
SELECT AVG(Price) AS AverageProductPrice
FROM Products;

Formatting the Output

Averages frequently result in long, messy decimal numbers, like 18.234598. You usually want to round this output to make it presentable for users.

PostgreSQL offers the built-in ROUND() function to solve this aesthetic issue. You can aggressively wrap ROUND() around your AVG() function to trim the decimals.

Rounded AVG Example:

-- Round the average price strictly to 2 decimal places
SELECT ROUND(AVG(Price), 2) AS CleanAverage
FROM Products;

Filtering the Average

Calculating the holistic average of an entire table is rarely what you need. You often want the precise average of a smaller, segmented group of data.

Applying a WHERE clause ensures the average reflects exactly what you need. For example, finding the average test score for only a specific classroom.

Filtered AVG Example:

-- Find the average price of only the most expensive items
SELECT AVG(Price) AS HighTierAverage
FROM Products
WHERE Price > 20;

Dealing with NULL Averages

If the filtered dataset contains zero rows, the function cannot calculate a mean. It will return a flat NULL value to prevent mathematical division by zero errors.

If your application requires a fallback zero, you must utilize the COALESCE() wrapper. This ensures your frontend receives a valid number regardless of the database state.

Summary

The AVG() function is mandatory for establishing performance baselines and trends. It safely excludes empty data points to keep mathematical integrity pristine.

Always consider utilizing the ROUND() function to keep your data outputs legible.

Exercise

How does the AVG() function treat rows that contain a NULL value?