SQL COUNT() Function

« Previous Chapter Next Chapter »

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.

SQL COUNT(column_name) Example

We have the following "Purchases" table:

PU_ID OrderDate OrderPrice Customer
1 2015/11/12 1000 Karmen
2 2015/10/23 1600 Tendulkar
3 2015/09/02 700 Karmen
4 2015/09/03 300 Karmen
5 2015/08/30 2000 Jensen
6 2015/10/04 100 Tendulkar

Now we want to count the number of Purchases from "Customer Tendulkar".

We use the following SQL statement:

SELECT COUNT(Customer) AS CustomerTendulkar FROM Purchases
WHERE Customer='Tendulkar'

The result of the SQL statement above will be 2, because the customer Tendulkar has made 2 Purchases in total:

CustomerTendulkar
2


SQL COUNT(*) Example

If we omit the WHERE clause, like this:

SELECT COUNT(*) AS NumberOfPurchases FROM Purchases

The result-set will look like this:

NumberOfPurchases
6

which is the total number of rows in the table.

SQL COUNT(DISTINCT column_name) Example

Now we want to count the number of unique customers in the "Purchases" table.

We use the following SQL statement:

SELECT COUNT(DISTINCT Customer) AS NumberOfCustomers FROM Purchases

The result-set will look like this:

NumberOfCustomers
3

which is the number of unique customers (Karmen, Tendulkar, and Jensen) in the "Purchases" table.


« Previous Chapter Next Chapter »

Have Any Suggestion? We Are Waiting To Hear from YOU!

Your Query was successfully sent!