0
0
SQLquery~5 mins

AVG function in SQL

Choose your learning style9 modes available
Introduction
The AVG function helps you find the average value of numbers in a column. It is like finding the middle point of a group of numbers.
To find the average score of students in a class.
To calculate the average price of products in a store.
To see the average temperature over a week.
To find the average salary of employees in a company.
To check the average rating of a product from customer reviews.
Syntax
SQL
SELECT AVG(column_name) FROM table_name;
AVG works only on numeric columns.
It ignores empty or NULL values when calculating the average.
Examples
Finds the average price of all products.
SQL
SELECT AVG(price) FROM products;
Finds the average score for Math exams only.
SQL
SELECT AVG(score) FROM exams WHERE subject = 'Math';
Calculates the average salary of employees in the Sales department.
SQL
SELECT AVG(salary) FROM employees WHERE department = 'Sales';
Sample Program
This creates a sales table, adds some amounts including a NULL, and finds the average amount ignoring the NULL.
SQL
CREATE TABLE sales (
  id INT,
  amount DECIMAL(10,2)
);

INSERT INTO sales (id, amount) VALUES
(1, 100.00),
(2, 150.00),
(3, 200.00),
(4, NULL);

SELECT AVG(amount) AS average_amount FROM sales;
OutputSuccess
Important Notes
AVG ignores NULL values, so they do not affect the average calculation.
If all values are NULL, AVG returns NULL.
You can use AVG with GROUP BY to find averages for different groups.
Summary
AVG calculates the average of numeric values in a column.
It skips NULL values automatically.
Useful for quick summary statistics like average price, score, or salary.