Hook: Interviewers love AVG because it looks simple, but it quietly tests whether you know how SQL treats NULL, types, and grouping.
Question: What does AVG do in SQL?
Answer: AVG is an aggregate function that returns the arithmetic mean, which is the sum of the values divided by how many values there are. It ignores NULL values, so missing data does not count in the calculation. If there are no non-NULL rows, the result is NULL, not zero.
Interview-Ready Answer: In SQL, AVG calculates the arithmetic mean of a numeric column. It skips NULLs automatically, so only real values count in the numerator and denominator. One detail interviewers like is that the return type and precision can depend on the database and input type, so if I need exact decimals, I often cast explicitly.
AVG really meansDetailed Explanation: Think of AVG as a two-step shortcut: add the numbers, then divide by how many numbers you actually have. In SQL, that is an aggregate operation, meaning it combines many rows into one result. The key idea is that AVG is not “middle value” or “most common value”; it is specifically the arithmetic mean.
NULL.NULL values.NULL because there is nothing to average.This is why AVG is often mentally paired with SUM and COUNT. In fact, many interview answers are stronger if you can say that AVG(x) is conceptually like SUM(x) / COUNT(x), except SQL handles the NULL rules for you.
| Function | What it returns | Best for |
|---|---|---|
AVG | Mean | Typical value |
SUM | Total | Volume |
COUNT | Number of rows | Frequency |
MEDIAN | Middle value | Skewed data |
Why this matters: average can be misleading if one value is huge. For example, salaries of 50k, 52k, and 400k give an average of 167k, which does not describe a typical employee well. That is a great interview insight: the function is mathematically correct, but sometimes not the best business metric.
Different databases may return different result types. Some systems promote integer inputs to a decimal or numeric result; others may preserve or widen types differently. The safe habit is to cast when precision matters, for example averaging cents, ratings, or ratios. Also, do not average text dates or booleans directly unless your database explicitly allows a numeric conversion, because that behavior is not portable.
Performance note: AVG is usually O(n) over the rows in the group because the engine must inspect each row once. Memory usage is typically small because the engine only needs a running sum and count, not the full list of values. If you add GROUP BY, the database may use hashing or sorting, and cost then depends on the number of groups and indexes, but the aggregate itself is still linear in the number of rows scanned.
AVG(NULL) over all-null input returns NULL.AVG ignores NULL values instead of treating them as zero.WHERE, you change the denominator because only surviving rows are averaged.Memory Hook: Picture a classroom average: you add only the students who actually showed up, then divide by the number who showed up. Empty seats do not count.
Real-World Example: In a checkout service, a data analyst might track the average order amount per day to spot unusual drops. If the average suddenly falls, it could mean discounts are too aggressive, a payment bug is causing partial orders, or high-value items are not being sold.
What goes wrong: suppose a team accidentally stores failed payments as 0 instead of NULL. The daily AVG(order_amount) drops sharply, dashboards show a false revenue problem, and on-call engineers waste time investigating a non-issue. In logs, you might see lots of “zero-value order” rows; users might not see failures directly, but leadership sees misleading KPIs and makes bad decisions. The fix is to store missing values as NULL when the value is truly unknown, and to filter or clean the data before averaging.
-- Demonstration of AVG with NULL handling, grouping, and a safe decimal cast.
-- This script is standard SQL and runs in many databases with minor dialect support.
DROP TABLE IF EXISTS sales;
CREATE TABLE sales (
region VARCHAR(20),
amount DECIMAL(10,2)
);
INSERT INTO sales (region, amount) VALUES
('East', 100.00),
('East', 200.00),
('East', NULL), -- Missing value: AVG must ignore it
('West', 50.00),
('West', 70.00),
('West', 90.00),
('North', NULL); -- All-null group should produce NULL
-- Overall average: NULL rows are ignored automatically.
SELECT AVG(amount) AS overall_avg_amount
FROM sales;
-- Average per region: grouped averages are computed independently.
SELECT
region,
AVG(amount) AS avg_amount
FROM sales
GROUP BY region
ORDER BY region;
-- Safe, explicit arithmetic version for learning:
-- SUM/COUNT explains what AVG is doing conceptually.
-- We use NULLIF to avoid division by zero if all values are NULL.
SELECT
region,
SUM(amount) / NULLIF(COUNT(amount), 0) AS avg_amount_manual
FROM sales
GROUP BY region
ORDER BY region;
-- Edge case: if you average only NULLs, result is NULL.
SELECT AVG(amount) AS avg_of_only_nulls
FROM sales
WHERE region = 'North';
-- If you need a readable default instead of NULL, use COALESCE.
-- Be careful: replacing NULL with 0 changes the meaning.
SELECT
COALESCE(AVG(amount), 0) AS avg_or_zero
FROM sales
WHERE region = 'North';
Follow-up & Tricky Questions:
NULL values in AVG? They are ignored, so they do not affect either the total or the count. If every value is NULL, the result is NULL.AVG(x) related to SUM(x) and COUNT(x)? Conceptually it is SUM(x) / COUNT(x), using only non-NULL values. That mental model helps when you need custom logic or filters.AVG with GROUP BY? Yes. Each group gets its own average, which is how you build “average by region,” “average by month,” or “average by user type.”AVG and MEDIAN? AVG uses every value and can be pulled by outliers; MEDIAN is the middle value and is more robust when data is skewed.Tricky / gotcha questions:
AVG(0) return NULL because zero is “empty”? No. Zero is a real numeric value, so it counts as a valid row and the result is zero if all values are zero.AVG(CASE WHEN condition THEN amount END), what happens to rows that do not match? The CASE returns NULL for non-matching rows, and AVG ignores them. This is a common and clean filtering pattern.AVG always exact? Not necessarily. Exactness depends on the underlying data type and database engine, so for money or critical metrics, use the right numeric type and cast intentionally.Common Mistakes:
NULL as zero. Correction: AVG ignores NULL; it does not convert it to 0.AVG can be skewed by outliers. Correction: use MEDIAN or percentile logic when you need a “typical” value for skewed data.COALESCE(AVG(x), 0) too casually. Correction: returning 0 for “no data” may hide a data-quality problem; only do this when 0 is a meaningful business default.Memory Hook: “Average = sum of the people who showed up, divided by the people who showed up.” Missing values do not attend the meeting.
Cheat Sheet:
AVG computes the arithmetic mean.NULL values.AVG with no non-NULL rows returns NULL.GROUP BY for per-group averages.MEDIAN for skewed data.Practice Tasks:
employees table and ignores missing salaries.0 instead of NULL, then explain whether that is a good idea.