SQL Count

COUNT() returns the number of rows or values in a result set. Learn COUNT(*), COUNT(column), and COUNT(DISTINCT) with real examples.

On this page

SQL COUNT Function

The COUNT() function returns the number of rows in a result set. It is commonly used for reporting and analytics.

COUNT Syntax

SELECT COUNT(*)
FROM table_name;

COUNT(*)

COUNT(*) counts all rows returned by the query, including rows that contain NULL values in some columns.

SELECT COUNT(*) AS total_customers
FROM customers;

COUNT(column)

COUNT(column) counts only the rows where the specified column is NOT NULL.

SELECT COUNT(email) AS customers_with_email
FROM customers;

COUNT(DISTINCT column)

COUNT(DISTINCT column) counts the number of unique non-NULL values.

SELECT COUNT(DISTINCT country) AS unique_countries
FROM customers;

COUNT with WHERE

You can filter rows before counting using WHERE.

SELECT COUNT(*) AS active_customers
FROM customers
WHERE status = 'active';

COUNT with GROUP BY

To count rows per group, combine COUNT with GROUP BY.

SELECT country, COUNT(*) AS total_customers
FROM customers
GROUP BY country
ORDER BY total_customers DESC;

NULL Behavior

  • COUNT(*) counts rows, regardless of NULL values in columns
  • COUNT(column) ignores rows where the column is NULL
  • COUNT(DISTINCT column) ignores NULL values as well

Common Mistakes

  • Using COUNT(column) and expecting it to count NULL values
  • Forgetting that WHERE filters rows before COUNT runs
  • Using COUNT(*) without grouping when you expected per-category totals

Performance Note

On large tables, indexes can help some COUNT queries, especially when combined with WHERE filters. However, the exact performance depends on your database engine and query.

Next Step

Continue with SQL SUM to learn how to total numeric values.