How to get the average of a column in SQL

Published on

Let's say we have a database table named orders with columns: id, name, and cost.

1John Doe134.00
2Eve Marcus146.00
3Lucy Tomlin20.00
4Bill Carson118.00
5John Doe102.00
6Lucy Tomlin90.00
7Lucy Tomlin34.00
8Bill Carson122.00

In our application we might want to find the average cost of all orders, this is a perfect use case for the AVG aggregate function. Here's what our query would look like:

SELECT AVG(cost) as average_cost FROM orders

And here's the result:


But we can take this even further, what if we wanted to get an average of each persons orders? We can alter our select to include the order name and then grouping on it. So our new query looks like this:

SELECT name, AVG(cost) as average_cost FROM orders GROUP BY name;

And this is our result:

John Doe118.00
Eve Marcus146.00
Lucy Tomlin48.00
Bill Carson120.00