Careeroza
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)
| Form | Counts |
|---|---|
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
| AllOrders | HandledOrders | DistinctCustomers |
|---|---|---|
| 8 | 7 | 6 |
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 |