SQL AVG
The sum divided by the count — but the count only includes non-NULL rows, which matters more than it sounds.
What & Why
AVG(column) computes the mean — sum divided by count. Critically, both the sum and the count ignore NULL values entirely, which is covered in depth in the final lesson of this series.
See How It Works
BUSINESS QUESTION
Average spend across the campaign portfolio.
| id | name | channel | spend | start_date | end_date | status | target_segment |
|---|---|---|---|---|---|---|---|
| 1 | Spring Launch | google_ads | 55000.00 | 2024-01-15 | 2024-03-31 | active | smb |
| 2 | Retention Webinar | 45000.00 | 2024-02-10 | 2024-04-15 | active | enterprise | |
| 3 | Finance Retargeting | 50000.00 | 2024-03-12 | 2024-05-31 | active | enterprise | |
| 4 | Enterprise Search | google_ads | 60000.00 | 2024-04-01 | 2024-06-30 | active | enterprise |
Watch AVG divide the sum by the countStep 1 of 2
SUM(spend) = 55,000 + 45,000 + 50,000 + 60,000
| id | campaign | spend | sum contribution |
|---|---|---|---|
| 1 | Spring Launch | 55,000.00 | + 55,000.00 |
| 2 | Retention Webinar | 45,000.00 | + 45,000.00 |
| 3 | Finance Retargeting | 50,000.00 | + 50,000.00 |
| 4 | Enterprise Search | 60,000.00 | + 60,000.00 |
SUM(spend)
210,000First, AVG adds the four non-NULL spend values.
EXAMPLE QUERY
SELECT AVG(spend) AS avg_spend
FROM marketing.campaigns;Now You Try
Practice this concept
Marketing wants average lead score by source.
Available schema
marketingPrefix tables with marketing.table_name.
sourceavg_lead_scoremarketing.leads| Column | Type |
|---|---|
| id | integer |
| campaign_id | integer |
| text | |
| created_at | timestamp with time zone |
| qualified_at | timestamp with time zone |
| converted_at | timestamp with time zone |
| lead_score | integer |
| source | text |
| country | text |
| archive_status | text |
query.sql
Sign up free to try it on a real business scenario