SQL Cookbook Lesson
How to find the average of a numeric column in SQL
Learn how to find the average of a numeric column in SQL with examples and explanations from SQLPad.
Problem
You are working with a SQL database and you want to calculate the average of a numeric column. How can you accomplish this task?
Sample Data
Let's assume we have a table named 'Orders' with the following data:
| OrderID | Product | Quantity | Price |
|---|---|---|---|
| 1 | Apple | 10 | 20 |
| 2 | Orange | 15 | 25 |
| 3 | Banana | 20 | 30 |
| 4 | Mango | 25 | 35 |
| 5 | Grape | 30 | 40 |
We want to find the average price of the products.
MySQL Solution
SELECT AVG(Price) as AveragePrice FROM Orders;
PostgreSQL Solution
SELECT AVG(Price) as AveragePrice FROM Orders;
Explanation
In both MySQL and PostgreSQL, the AVG() function is used to return the average value of a numeric column. It calculates the sum of the values in the column and then divides by the count of values.
In the given solution, we are using the AVG() function to calculate the average of the 'Price' column from the 'Orders' table. The 'as' keyword is used to rename the column header in the output to 'AveragePrice'.
This function will work the same way in both MySQL and PostgreSQL, so the solution is the same for both.