SQL COUNT Function
beginneraggregation
2 min read
What is COUNT?
COUNT is an aggregate function that returns the number of rows matching a condition. It is one of the most frequently used SQL functions.
Variants
COUNT(*)— Counts all rows, including those with NULLs.COUNT(column)— Counts non-NULL values in the specified column.COUNT(DISTINCT column)— Counts unique non-NULL values.
Syntax
SELECT COUNT(*) FROM table_name;
SELECT COUNT(column_name) FROM table_name;
SELECT COUNT(DISTINCT column_name) FROM table_name;When to Use
- Getting total record counts
- Counting records per group with GROUP BY
- Checking if related records exist
Key Points
- **COUNT(*) vs COUNT(column)** —
COUNT(*)includes NULLs;COUNT(column)excludes them. - With GROUP BY — Use
COUNTwithGROUP BYto count records per category. - With WHERE — Apply
WHEREbefore counting to filter the source rows. - DISTINCT —
COUNT(DISTINCT grade)counts the number of unique grades. - Performance —
COUNT(*)on large tables can be slow. Consider approximate counts for large datasets.
Guided Practice
Solve the challenge below. Use hints when stuck and check your answer for instant feedback.
Practice challengeGuided learning mode
SQL COUNT Function Challenge
Write a query that solve this task: count all rows in the students table.
Expected result
A single number representing the total number of students.
Hidden checks
- Returned rows and values
- Output columns and result shape
- Final database state after the query runs
Lesson guidance
What is COUNT?
Initializing database...Each run starts from fresh sample data.
More Examples
Count students per grade
Group students by grade and count each group.
Initializing database...Each run starts from fresh sample data.
Count distinct categories
Count how many unique product categories exist.
Initializing database...Each run starts from fresh sample data.
Frequently Asked Questions
What is the difference between COUNT(*) and COUNT(column)?
COUNT(*) counts all rows including those where column values are NULL. COUNT(column) counts only rows where the specified column is not NULL.
Is COUNT(*) slow on large tables?
In PostgreSQL, COUNT(*) must scan the table or an index because MVCC means each transaction may see different rows. For approximate counts, query pg_class.reltuples.