SQL: aggregate functions (COUNT, SUM, AVG, MAX)
Computer Science · Databases
Question 1 of 10
0employees name | dept | salary Fay | Sales | 6000 Hana | IT | 6800 Ben | IT | 2300 Gus | Sales | 7000 Dev | IT | 6400 What single value does this query return? SELECT COUNT(*) FROM employees;
Decimals (0.75 or 0,75), fractions (3/4) and mixed numbers (1 1/2) are accepted. Do not use thousands separators.
How to type your answer
- Fractions: 3/4. Mixed numbers: 1 1/2.
- Decimals with a point or a comma: 0.75 or 0,75.
- Negative numbers start with a minus: -3/4.
- Percentages need the % sign: 75%.
Stuck? Read the explanation
Unlocks at a streak of 5 correct answers in a row.
Embed this practice on your site or class page
Paste this HTML into your page. Students practise right there; it is free and needs no account.
SQL: aggregate functions (COUNT, SUM, AVG, MAX) explained
Aggregate functions in SQL take the values from many rows and return a single value. COUNT counts rows, SUM adds the values, AVG gives their mean, and MAX and MIN give the largest and smallest values. They summarise a table rather than list its rows.
A WHERE clause filters the rows before the aggregate function is applied, so the function only sees the rows that remain. Aggregate functions also handle NULL, which means "no value", with care. SUM, AVG, MIN and MAX skip NULL values. COUNT(column) counts only the rows where that column is not NULL, while COUNT(*) counts every row, including rows that have NULL in other columns. AVG is the sum of the non-NULL values divided by how many there are.
Caveat: without a GROUP BY clause, standard SQL does not allow a plain column next to an aggregate, because it cannot tell which row that column should come from.
Worked example
Here is a hypothetical employees table, in which Dev's salary is NULL.
name | dept | salary
Ava | Sales | 3000
Ben | IT | 4000
Cara | Sales | 5000
Dev | Sales | NULL
What single value does this query return?
SELECT AVG(salary) FROM employees WHERE dept = 'Sales';
- WHERE keeps the Sales rows: Ava, Cara and Dev.
- AVG skips Dev's NULL, so it uses 3000 and 5000.
- AVG = (3000 + 5000) ÷ 2 = 4000.
The query returns 4000.
What you will practise
New numbers every time you practise. Levels: Easy, Medium, Hard. Each answer is followed by a worked explanation.
Example questions
Easy
employees name | dept | salary Eli | Sales | 7500 Fay | IT | 6700 Hana | Sales | 6300 Gus | IT | 4400 Cara | Sales | 3600
What single value does this query return? SELECT COUNT(*) FROM employees;
Medium
employees name | dept | salary Ben | Sales | 2700 Ava | IT | 4800 Hana | Sales | 2100 Cara | IT | 7100 Dev | Sales | 7000
What single value does this query return? SELECT AVG(salary) FROM employees WHERE dept = 'IT';
Hard
employees name | dept | salary Cara | Sales | NULL Eli | IT | 4500 Ben | IT | 2600 Fay | Sales | 7100 Gus | IT | 6600 Hana | IT | 8000
What single value does this query return? SELECT COUNT(*) FROM employees WHERE dept = 'Sales';