MySQL AVG

MySQL AVG

MySQL AVG Function

The AVG() function in MySQL is an aggregate function that returns the average value of a numeric column. It is typically used for statistical analysis to calculate the mean values in a dataset.

Syntax

AVG(expression)
  • expression: The numeric column or expression to compute the average. The values in this column are used to calculate the average.

How It Works

  • The the AVG() function calculates the average of all non-NULL values in the specified column.
  • If the column contains any NULL values, they are ignored during the calculation.
  • It returns a floating-point value.

Examples

1. Basic Usage

Calculate the average salary from the employees table:

SELECT AVG(salary) AS average_salary FROM employees;

Output:

average_salary -------------- 5000

2. Using with Conditions (WHERE)

Calculate the average salary of employees in a specific department:

SELECT AVG(salary) AS average_salary FROM employees WHERE department_id = 2;

3. Using with GROUP BY

Calculate the average salary for each department:

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

Output:

department_id | average_salary --------------|---------------- 1 | 4500 2 | 5200 3 | 4800

4. Using with HAVING

Filter groups after calculating the average salary:

SELECT department_id, AVG(salary) AS average_salary FROM employees GROUP BY department_id HAVING AVG(salary) > 5000;

5. Calculating Average for a Subset of Data

Calculate the average salary for employees older than 30:

SELECT AVG(salary) AS average_salary FROM employees WHERE age > 30;

Key Considerations

  1. Handling NULL Values:

    • NULL values are ignored by the AVG() function.
  2. Data Type of Result:

    • The result of AVG() is always a floating-point number. Even if the input column has integer values, the result may include decimal places.
  3. Performance:

    • The AVG() function can be slow on large datasets without proper indexing, especially when used with conditions or grouped data.

Common Use Cases

  1. Average of Numeric Columns:
    • Calculate averages of numeric values like salary, price, age, etc.
  2. Comparative Analysis:
    • Compare average values across different groups or categories (e.g., average sales per region).
  3. Trend Analysis:
    • Track trends in averages over time by grouping by date or period.

Conclusion

The AVG() function is a simple yet powerful aggregate function for calculating averages in MySQL. Whether used for basic computations, conditional filtering, or grouping data, it provides useful insights into the central tendency of numeric datasets. It integrates well with other SQL features like WHERE, GROUP BY, and HAVING, making it a valuable tool for statistical analysis in SQL queries.

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close