Averages and SQL Functions

Which SQL function is used to calculate the average marks of students?

The function is AVG(). Learn how to use it to find each student's average marks with GROUP BY, handle NULL scores and round the result to one decimal place.

On this page
  1. Average marks for one student
  2. Average marks for every student
  3. Rounding to one decimal place
  4. Missing marks
  5. Integer marks in SQL Server
  6. When the marks are in separate columns

The function is AVG(). It adds the non-NULL values in a column and divides by how many values there were.

Average marks for one student

SELECT AVG(score) AS average_mark
FROM test_results
WHERE student_id = 7;

Average marks for every student

SELECT student_id, AVG(score) AS average_mark
FROM test_results
GROUP BY student_id;

GROUP BY gives one row per student. Without it, AVG() returns one number for the whole result.

Rounding to one decimal place

SELECT student_id, ROUND(AVG(score), 1) AS average_mark
FROM test_results
GROUP BY student_id;

Round after averaging, not before, so the average is calculated from the full scores.

Missing marks

AVG() skips NULL marks. A student with marks of 80 and 90 and one NULL gets an average of 85. If the NULL counted as zero, the average would be about 56.7 instead.

Integer marks in SQL Server

In SQL Server, AVG() of an int column returns an int, so an average of 84.33 comes back as 84. Cast the column first:

SELECT student_id, AVG(CAST(score AS DECIMAL(10, 2))) AS average_mark
FROM test_results
GROUP BY student_id;

When the marks are in separate columns

If each subject has its own column instead of its own row, you want the average across the columns of each row. That takes plain arithmetic, and it is covered in how to calculate average for each row in SQL.

The complete guide to averages and sql functions

How to Calculate the Average for Each Row in SQL
Read the guide

Keep exploring

Guides from other topics

All topics →