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_id | name | department | salary | age |
---|---|---|---|---|
1 | Alice | HR | 50000 | 28 |
2 | Bob | IT | 60000 | 32 |
3 | Charlie | IT | 70000 | 35 |
4 | Diana | HR | 55000 | 29 |
5 | Eve | Sales | 65000 | 30 |
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:
department | average_salary |
---|---|
HR | 52500 |
IT | 65000 |
Sales | 65000 |
Real-World Applications of AVG
- Salary Analysis: Determine average salaries across departments or industries.
- Performance Metrics: Calculate the average score, completion time, or sales.
- 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!