Pathubs SQL Curriculum • Module 08

SQL COUNT

Master the fundamental SQL aggregate function: understand COUNT(*) vs COUNT(column) vs COUNT(DISTINCT column), learn how NULL values are handled, and combine COUNT with WHERE filters.

⏱️ Estimated Time:45 Minutes
🎯 Level:Beginner
📊 Track:Data Analytics & SQL Mastery
✨ Mode:Interactive Aggregation & Counting Lab
1

Introduction

In data analysis and reporting, one of the most common questions is: "How many items are there?"

  • How many customers registered this month?
  • How many orders were placed today?
  • How many employees work in the Sales department?
  • How many customers provided a valid contact phone number?

SQL answers all these questions through the COUNT aggregate function.

2

What Is COUNT?

COUNT is an aggregate function. Instead of returning multiple individual rows, it reads a set of rows and summarizes them into a single numeric count.

SELECT COUNT(*)
FROM customers;

If your table has 500 customers, this query returns a single row containing the number 500.

3

COUNT(*) — Counting Rows

COUNT(*) counts total rows in the result set. It does not look at any specific column, and it counts every row regardless of whether individual columns contain NULL.

SELECT COUNT(*)
FROM employees;
Diagram 1: COUNT(*) Evaluates Complete Rows
Row 1 (Rahul, 62k, 9876543210) ✓
Row 2 (Priya, 48k, NULL) ✓
Row 3 (Amit, 85k, 9123456789) ✓
Row 4 (Sneha, NULL, NULL) ✓
➔ COUNT(*) ➔
Result: 4 Rows
(All rows counted)
4

COUNT(column) — Counting Non-NULL Values

When you pass a specific column name into COUNT, such as COUNT(phone), SQL counts only rows where that column has a non-NULL value.

SELECT COUNT(phone)
FROM customers;
💡
Rule of Thumb: Use COUNT(*) when you want to know how many rows exist. Use COUNT(column) when you want to know how many records have a value in that column.
Diagram 2: COUNT(column) Excludes NULLs
phone = '9876543210' ✓ (Counted)
phone = NULL ✗ (Skipped)
phone = '9123456789' ✓ (Counted)
phone = NULL ✗ (Skipped)
➔ COUNT(phone) ➔
Result: 2
(Only 2 non-NULL phones)
5

COUNT(*) vs COUNT(column) Side-by-Side

Consider the following 4-row customer sample table:

idnamephone
1Aarav9876543210
2DiyaNULL
3Ishaan9123456789
4RiyaNULL
SELECT COUNT(*)
4

Counts all 4 customer rows in the table.

SELECT COUNT(phone)
2

Counts only the 2 customers with non-NULL phone numbers.

6

COUNT(DISTINCT column)

To count only unique, distinct non-NULL values, prefix the column with DISTINCT:

SELECT COUNT(DISTINCT city)
FROM customers;

If your table has 5 rows with cities: ['Mumbai', 'Mumbai', 'Delhi', 'Pune', 'Pune'], COUNT(DISTINCT city) returns 3 (Mumbai, Delhi, Pune).

Diagram 3: The Three Flavors of COUNT
COUNT(*)
Counts every row (including NULLs)
COUNT(column)
Counts non-NULL values
COUNT(DISTINCT column)
Counts unique non-NULL values
7

COUNT With WHERE

Combining COUNT with WHERE allows you to calculate filtered totals:

SELECT COUNT(*)
FROM employees
WHERE department = 'Sales';

Mental Execution Flow:

  1. The database scans the employees table.
  2. The WHERE department = 'Sales' condition filters for only sales personnel.
  3. COUNT(*) counts how many rows passed that filter.
  4. A single summary number is returned.
8

COUNT and NULL In-Depth

Understanding how NULL interacts with counting functions prevents critical business metric errors:

SyntaxHow NULL is HandledDuplicates HandledPrimary Use Case
COUNT(*)Included (Counts the row)IncludedTotal record count in table / group
COUNT(col)Ignored (NULL rows skipped)IncludedCount of recorded / completed entries
COUNT(DISTINCT col)Ignored (NULL skipped)DeduplicatedCount of unique non-NULL categories / entities
9

COUNT With Column Aliases

By default, aggregate queries return unnamed column headers like count. Use AS to assign intuitive column names:

SELECT COUNT(*) AS total_active_customers
FROM customers;
10

Understanding COUNT Results

Without a GROUP BY clause, COUNT always collapses all matching rows into a single scalar row. Even if 1,000,000 rows match your filter, the response is exactly 1 row containing the total number.

Live Interactive COUNT Lab
📦 Table Data & Row Count Status8 Customer Records
#namecityphoneCount Status
1Aarav PatelMumbai9876543210Row counted by COUNT(*)
2Diya SharmaDelhiNULLRow counted by COUNT(*)
3Ishaan VermaMumbai9123456789Row counted by COUNT(*)
4Riya GuptaPune9876543210Row counted by COUNT(*)
5Kabir SinghBengaluruNULLRow counted by COUNT(*)
6Ananya RoyDelhi9988776655Row counted by COUNT(*)
7Rohan MehtaMumbaiNULLRow counted by COUNT(*)
8Tara NairPune9845123456Row counted by COUNT(*)
✍️ SQL Aggregate Query● Scalar Output
SELECT COUNT(*) AS total_customers
FROM customers;
8
Output column: total_customers
8 of 8 candidate rows included
11

Common COUNT Mistakes

1. Using COUNT(column) to Count Total Rows

If you write COUNT(phone) thinking it counts all users, any user with a NULL phone will be missing from your total count. Always use COUNT(*) for total row counts.

2. Confusing COUNT(column) With COUNT(DISTINCT column)

COUNT(city) returns total city entries (including duplicates). COUNT(DISTINCT city) deduplicates and counts unique cities.

3. Forgetting the WHERE Clause

Omitting WHERE aggregates across the entire table. Always filter first when counting specific departments, statuses, or date ranges.

🧠 Interactive Challenge: Predict The Result (1 of 3)
SELECT COUNT(phone) FROM customers;
With 8 total customer rows where 3 customers have NULL phone numbers, what number does this return?
12

Practical Step-by-Step Exercises

Task GoalTarget TableRequired SQL SolutionPattern Used
1. Count All CustomerscustomersSELECT COUNT(*) FROM customers;Total row count
2. Count Valid Phone NumberscustomersSELECT COUNT(phone) FROM customers;Non-NULL count
3. Count Unique Customer CitiescustomersSELECT COUNT(DISTINCT city) FROM customers;Distinct non-NULL count
4. Count Sales Department StaffemployeesSELECT COUNT(*) FROM employees WHERE department = 'Sales';WHERE + COUNT
5. Unique Cities With Active SalesemployeesSELECT COUNT(DISTINCT city) FROM employees WHERE department = 'Sales';WHERE + COUNT(DISTINCT)
13

COUNT Best Practices

  • Default to COUNT(*): Use COUNT(*) for general row counts. Database optimizers are specifically tuned to execute COUNT(*) efficiently.
  • Always Alias Aggregate Results: Use AS total_orders to make downstream API and reporting tools readable.
  • Be Conscious of NULL Semantics: Remember that COUNT(col) silently drops NULL rows.
  • Combine With WHERE for Segment Counts: Apply filters before aggregation to calculate active, verified, or pending records cleanly.
14

What You Should Know Now

  • COUNT(*): Counts all rows including NULLs
  • COUNT(col): Counts non-NULL values in that column
  • COUNT(DISTINCT col): Counts unique non-NULL values
  • WHERE + COUNT: Filters rows before counting
  • Aliases: Gives meaningful names to aggregate output
  • Scalar Output: Produces a single numeric summary

🎯 Knowledge Check Quiz: SQL COUNT

Test your understanding of row counting, non-NULL aggregation, and distinct counting patterns.

1. What is the primary function of the SQL COUNT aggregate function?
2. How does COUNT(*) handle rows that contain NULL values in one or more columns?
3. What is the key difference between COUNT(*) and COUNT(email)?
4. Given the emails ["a@x.com", "b@x.com", "a@x.com", NULL], what is the output of SELECT COUNT(DISTINCT email)?
5. How does a WHERE clause interact with COUNT in a SQL statement?
6. Why should you provide an alias (e.g. COUNT(*) AS total_users) for aggregate queries?
7. If a table has 0 rows matching a WHERE condition, what does SELECT COUNT(*) return?
8. Which query correctly counts how many employees in the "Engineering" department have a recorded phone number?