What are 'Scalar Functions' in SQL, and how do they differ from 'Aggregate Functions'?
Instruction: Define both scalar and aggregate functions and illustrate their differences.
Updated
Official answer
A scalar expression produces one value per evaluation. It may take several arguments, as with COALESCE, rather than always exactly one input. An aggregate summarizes rows within a group. Replacing one with the other generally changes the question being answered.
This PostgreSQL example normalizes labels before grouping:
WITH sales(region, amount) AS (
VALUES ('East',10), ('EAST',20), ('West',NULL::integer)
)
SELECT lower(region) AS region,
COUNT(*) AS row_count, COUNT(amount) AS known_amounts,
SUM(amount) AS total
FROM sales
GROUP BY lower(region)
ORDER BY region;
The results are (east,2,2,30) and (west,1,0,NULL). LOWER is scalar; COUNT and SUM are aggregates. SUM ignores NULL inputs and returns NULL when there are no non-NULL values; COUNT(*) counts rows. Whether a missing amount should become zero is a business decision.
Aggregates can also be used as window functions with OVER to retain input rows. Choose the required output grain first, then measure performance without assuming fewer function calls preserve semantics.