PostgreSQL: AVG Function – Calculate the Average Value of a Column

Welcome to The Coding College, your trusted source for coding tutorials! Today, we’ll explore the AVG function in PostgreSQL, which is used to compute the average value of numeric data in a column.

What is the AVG Function?

The AVG function calculates the average of numeric values in a column. It’s particularly useful for analyzing trends, performance metrics, and other data insights.

Syntax

SELECT AVG(column_name)
FROM table_name
[WHERE condition];
  • column_name: The column containing numeric data.
  • WHERE: (Optional) Filters rows before computing the average.

Example: Sample Table

Let’s use the employees table:

employee_idnamedepartmentsalaryage
1AliceHR5000028
2BobIT6000032
3CharlieIT7000035
4DianaHR5500029
5EveSales6500030

Using the AVG Function

Example 1: Calculate the Average Salary

SELECT AVG(salary) AS average_salary
FROM employees;

Result:

average_salary
60000

Example 2: Calculate the Average Age

SELECT AVG(age) AS average_age
FROM employees;

Result:

average_age
30.8

Using AVG with Conditions

Example 3: Average Salary in the IT Department

SELECT AVG(salary) AS average_it_salary
FROM employees
WHERE department = 'IT';

Result:

average_it_salary
65000

Combining AVG with GROUP BY

Example 4: Average Salary by Department

SELECT department, AVG(salary) AS average_salary
FROM employees
GROUP BY department;

Result:

departmentaverage_salary
HR52500
IT65000
Sales65000

Real-World Applications of AVG

  1. Salary Analysis: Determine average salaries across departments or industries.
  2. Performance Metrics: Calculate the average score, completion time, or sales.
  3. Demographic Insights: Compute average age, income, or other demographic details.

Key Points to Remember

  • The AVG function ignores NULL values during calculations.
  • Use the ROUND() function to format the result for better readability:
SELECT ROUND(AVG(salary), 2) AS rounded_average_salary
FROM employees;

Learn More at The Coding College

Explore more PostgreSQL tutorials and coding insights at The Coding College. We prioritize user benefits and align with Google’s E-E-A-T guidelines for expertise, experience, authority, and trust.

Conclusion

The PostgreSQL AVG function is an indispensable tool for analyzing data and extracting meaningful insights. Whether you’re working on financial data, demographic statistics, or performance metrics, AVG makes it simple to find the average value.

Stay tuned to The Coding College for more PostgreSQL tips and programming tutorials!

Leave a Comment