HOME C C++ PYTHON JAVA HTML CSS JAVASCRIPT BOOTSTRAP JQUERY REACT PHP SQL AJAX JSON DATA SCIENCE AI

The SQL AVG() Function

The AVG() function returns the average value of a numeric column.

Example

Return the average price of all products:

SELECT AVG(Price)
FROM products ;

You can click on above box to edit the code and run again.

Output

avg price table


Note: NULL values are ignored.

Syntax

SELECT AVG (column_name)
FROM table_name
WHERE condition;

You can click on above box to edit the code and run again.

Output

Demo Products table


This product table is used for examples:


product table

Add a Where Clause


You can add a WHERE clause to specify conditions:

Example

Return the average price of products in Product_id 2:   
SELECT AVG(Price)
FROM products
WHERE Product_id = 2 ;

You can click on above box to edit the code and run again.

Output

avg price using where table

Use an Alias


It give the summarized column a name by using the AS keyword .

Example

Name the column "average price": 

SELECT AVG(Price) AS Average_price
FROM products ;

You can click on above box to edit the code and run again.

Output

avg with AS keyword

Higher Than Average


To list all records with a higher price than average, we can use the AVG()function in a sub query:

Example

Return all products with a higher price than the average price: 

SELECT * FROM products
WHERE price > ( SELECT AVG(Price) FROM Products);

You can click on above box to edit the code and run again.

Output

higher price then avg