Header Ads

Breaking News
recent

SQL COUNT(), AVG() and SUM() Functions

The SQL COUNT(), AVG() and SUM() Functions

The COUNT() function returns the number of rows that matches a specified criteria.
The AVG() function returns the average value of a numeric column.
The SUM() function returns the total sum of a numeric column.

COUNT() Syntax

SELECT COUNT(column_name)
FROM table_name
WHERE condition;

AVG() Syntax

SELECT AVG(column_name)
FROM table_name
WHERE condition;

SUM() Syntax

SELECT SUM(column_name)
FROM table_name
WHERE condition;

Demo Database

Below is a selection from the "Products" table in the Northwind sample database:
ProductIDProductNameSupplierIDCategoryIDUnitPrice
1Chais1110 boxes x 20 bags18
2Chang1124 - 12 oz bottles19
3Aniseed Syrup1212 - 550 ml bottles10
4Chef Anton's Cajun Seasoning2248 - 6 oz jars22
5Chef Anton's Gumbo Mix2236 boxes21.35


COUNT() Example

The following SQL statement finds the number of products:

Example

SELECT COUNT(ProductID)
FROM Products;
Try it Yourself »
Note: NULL values are not counted.

AVG() Example

The following SQL statement finds the average price of all products:

Example

SELECT AVG(Price)
FROM Products;
Try it Yourself »
Note: NULL values are ignored.

Demo Database

Below is a selection from the "OrderDetails" table in the Northwind sample database:
OrderDetailIDOrderIDProductIDQuantity
1102481112
2102484210
310248725
410249149
5102495140

SUM() Example

The following SQL statement finds the sum of the "Quantity" fields in the "OrderDetails" table:

Example

SELECT SUM(Quantity)
FROM OrderDetails;
Try it Yourself »
Note: NULL values are ignored.

Test Yourself With Exercises

Exercise:

Use the correct function to return the number of records that have the Price value set to 18.
SELECT (*)
FROM Products
 Price = 18;





                                                                         


No comments:

Powered by Blogger.