Friday, 15 January 2016

SQL COUNT() Function

SQL COUNT() Function


The COUNT() function returns the number of rows that matches a specified criteria.

SQL COUNT(column_name) Syntax

The COUNT(column_name) function returns the number of values (NULL values will not be counted) of the specified column:
SELECT COUNT(column_name) FROM table_name;

SQL COUNT(*) Syntax

The COUNT(*) function returns the number of records in a table:
SELECT COUNT(*) FROM table_name;

SQL COUNT(DISTINCT column_name) Syntax

The COUNT(DISTINCT column_name) function returns the number of distinct values of the specified column:
SELECT COUNT(DISTINCT column_name) FROM table_name;

Note: COUNT(DISTINCT) works with ORACLE and Microsoft SQL Server, but not with Microsoft Access.

Demo Database

In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Orders" table:
OrderIDCustomerIDEmployeeIDOrderDateShipperID
10265721996-07-251
102668731996-07-263
102672541996-07-291

SQL COUNT(column_name) Example

The following SQL statement counts the number of orders from "CustomerID"=7 from the "Orders" table:

Example:-

SELECT COUNT(CustomerID) AS OrdersFromCustomerID7 FROM Orders
WHERE CustomerID=7;

SQL COUNT(*) Example

The following SQL statement counts the total number of orders in the "Orders" table:

Example:-

SELECT COUNT(*) AS NumberOfOrders FROM Orders;

SQL COUNT(DISTINCT column_name) Example

The following SQL statement counts the number of unique customers in the "Orders" table:

Example:-

SELECT COUNT(DISTINCT CustomerID) AS NumberOfCustomers FROM Orders;

SQL AVG() Function

The AVG() Function

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

SQL AVG() Syntax

SELECT AVG(column_name) FROM table_name

Demo Database

In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Products" table:
ProductIDProductNameSupplierIDCategoryIDUnitPrice
1Chais1110 boxes x 20 bags18
2Chang1124 - 12 oz bottles19
3Aniseed Syrup1212 - 550 ml bottles10
4Chef Anton's Cajun Seasoning2248 - 6 oz jars21.35
5Chef Anton's Gumbo Mix2236 boxes25

SQL AVG() Example

The following SQL statement gets the average value of the "Price" column from the "Products" table:

Example:-

SELECT AVG(Price) AS PriceAverage FROM Products;

The following SQL statement selects the "ProductName" and "Price" records that have an above average price:

Example:-

SELECT ProductName, Price FROM Products
WHERE Price>(SELECT AVG(Price) FROM Products);