The COUNT() function returns the number of rows that matches a specified criteria.
The COUNT(column_name) function returns the number of values (NULL values will not be counted) of the specified column:
The COUNT(*) function returns the number of records in a table:
The COUNT(DISTINCT column_name) function returns the number of distinct values of the specified column:
Note: COUNT(DISTINCT) works with ORACLE and Microsoft SQL Server, but not with Microsoft Access.
We have the following "Orders" table:
| O_Id | OrderDate | OrderPrice | Customer |
|---|---|---|---|
| 1 | 2008/11/12 | 1000 | Hansen |
| 2 | 2008/10/23 | 1600 | Nilsen |
| 3 | 2008/09/02 | 700 | Hansen |
| 4 | 2008/09/03 | 300 | Hansen |
| 5 | 2008/08/30 | 2000 | Jensen |
| 6 | 2008/10/04 | 100 | Nilsen |
Now we want to count the number of orders from "Customer Nilsen".
We use the following SQL statement:
The result of the SQL statement above will be 2, because the customer Nilsen has made 2 orders in total:
| CustomerNilsen |
|---|
| 2 |
If we omit the WHERE clause, like this:
The result-set will look like this:
| NumberOfOrders |
|---|
| 6 |
which is the total number of rows in the table.
Now we want to count the number of unique customers in the "Orders" table.
We use the following SQL statement:
The result-set will look like this:
| NumberOfCustomers |
|---|
| 3 |
which is the number of unique customers (Hansen, Nilsen, and Jensen) in the "Orders" table.
| WEB HOSTING |
|---|
| Best Web Hosting |
| PHP MySQL Hosting |
| Best Hosting Coupons |
| UK Reseller Hosting |
| Cloud Hosting |
| Top Web Hosting |
| $7.95/mo SEO Hosting |
| Premium Website Design |
| WEB BUILDING |
|---|
| XML Editor - Free Trial! |
| FREE Website BUILDER |
| Free Website Templates Free CSS Templates |
| Make Your Own Website |
| W3SCHOOLS EXAMS |
|---|
|
Get Certified in: HTML, CSS, JavaScript, XML, PHP, and ASP |
| W3SCHOOLS BOOKS |
|---|
|
New Books: HTML, CSS JavaScript, and Ajax |
| STATISTICS |
|---|
|
Browser Statistics Browser OS Browser Display |
| SHARE THIS PAGE |
|---|