SQL Tutorial – AVG() – compute average in SQL.

Suppose, you have a table and you want to compute the average value for all the rows in a table or for some subset of rows. For example, you would like to compute the average LifeExpectancy of humans across all countries or may be you would like to compute the average LifeExpectancy by Continent.

Solution –

If you want to calculate the average value of a column, you can simply apply the AVG() function to that column.

SELECT
AVG(LifeExpectancy) as avg_life_expectancy
FROM
country

To calculate the average life expectancy by continent, we have to first group the data by Continent using the GROUP BY then apply the AVG() function to the LifeExpectancy column.

SELECT
Continent,
AVG(LifeExpectancy) as avg_life_expectancy
FROM
country
GROUP BY
Continent

If you like this post then please share it with others and subscribe to our blog below to learn data science.

Rating: 1 out of 5.