WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

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:

OrderID CustomerID EmployeeID OrderDate ShipperID
10555 8 2 2018-07-11 1
10566 87 3 2018-07-12 3
10567 25 4 2018-07-13 1

SQL COUNT(column_name) Example

The following SQL statement counts the number of orders from "CustomerID"87 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;