What is the difference between COUNT(*), COUNT(1), and COUNT(column_name) in SQL Server?
Short answer
COUNT(*) and COUNT(1) both count every row regardless of NULL values and generally perform the same, while COUNT(column_name) only counts rows where that specific column has a non NULL value, which is useful when you specifically want to know how many rows actually have data in…
Advertisement
AModel answer
COUNT(*) and COUNT(1) both count every row regardless of NULL values and generally perform the same, while COUNT(column_name) only counts rows where that specific column has a non NULL value, which is useful when you specifically want to know how many rows actually have data in a particular field.
SELECT COUNT(*) AS TotalCustomers, COUNT(PhoneNumber) AS CustomersWithPhone
FROM Customers;Real-world example
A customer database reports both the total number of customers and, separately, how many of them actually have a phone number on file, using COUNT(*) and COUNT(PhoneNumber) together in one query.
Likely follow-ups
- Does SQL Server treat COUNT(*) and COUNT(1) differently in terms of performance?
- How do you count only distinct values within a column?
Related topics