COUNT

The SQL COUNT() Function

COUNT() returns the number of rows that match a condition.

SELECT COUNT(column_name) FROM table_name WHERE condition;

COUNT(*) vs COUNT(column)

FormCounts
COUNT(*)all rows, including rows with NULLs
COUNT(column)rows where column is not NULL
COUNT(DISTINCT column)different non-NULL values

Example

The three forms of COUNT on the Orders table (order 105 has no EmployeeID):

SELECT COUNT(*) AS AllOrders,
       COUNT(EmployeeID) AS HandledOrders,
       COUNT(DISTINCT CustomerID) AS DistinctCustomers
FROM Orders;

Result: 1 row

AllOrdersHandledOrdersDistinctCustomers
876

COUNT with WHERE

Example

How many products cost more than 8?

SELECT COUNT(*) AS Expensive FROM Products
WHERE Price > 8;

Result: 1 row

Expensive
4