Dofactory.com
Dofactory.com
Earn income with your data and sql skills
Sign up and we'll send you the best freelance opportunities straight to your inbox.
We're building the largest freelancing marketplace for people like you.
By adding your name & email you agree to our terms, privacy and cookie policies.

SQL SELECT COUNT, SUM, and AVG

COUNT, SUM, and AVG are aggregate functions.

COUNT returns a count of the number of data values.

SUM returns the sum of the data values.

AVG returns the average of the data values.

For a list of all aggregate functions see our aggregate functions reference.

Example

#

Get the total number of products.

SELECT COUNT(Id) AS 'Product Count'
  FROM Product
Result
Product Count
78

Syntax

COUNT syntax.

SELECT COUNT(column-name)
  FROM table-name

SUM syntax.

SELECT SUM(column-name)
  FROM table-name

AVG syntax.

SELECT AVG(column-name)
  FROM table-name

More Examples

SELECT COUNT

CUSTOMER
Id
FirstName
LastName
City
Country
Phone
Problem: Get the total number of customers.
SELECT COUNT(Id) AS 'Customer Count'
  FROM Customer
Result
Customer Count
91

SELECT SUM

ORDER
Id
OrderDate
OrderNumber
CustomerId
TotalAmount
Problem: Calculate the total sales in 2013.
SELECT SUM(TotalAmount) AS 'Total Sales'
  FROM [Order]
 WHERE YEAR(OrderDate) = 2013
Result
Total Sales
658388.75

SELECT AVG

ORDER
Id
OrderDate
OrderNumber
CustomerId
TotalAmount
Problem: Calculate the average size of all orders.
SELECT AVG(TotalAmount) AS 'Avg Order'
  FROM [Order]
Result
Avg Order
1631.877819

You may also like



Last updated on Dec 21, 2023

Earn income with your data and sql skills
Sign up and we'll send you the best freelance opportunities straight to your inbox.
We're building the largest freelancing marketplace for people like you.
By adding your name & email you agree to our terms, privacy and cookie policies.