COUNT: Counting Rows and Non-Null Values
What you'll learn: How to use SQL's COUNT function to tally up rows in your results, including the difference between counting everything versus counting only non-null values.
The Core Idea
The COUNT() function is your go-to tool when you need to answer "how many?" questions about your data. Think of it like taking attendance in a classroom—you can either count every seat (COUNT(*)), or count only the students who actually showed up (COUNT(column_name)).
Two Flavors of COUNT
COUNT(*) counts all rows in your result set, regardless of whether any columns contain NULL values. It's the total headcount.
COUNT(column_name) counts only the rows where that specific column has a non-null value. If a row has NULL in that column, it doesn't get counted.
When to Use Each
Use COUNT(*) when you want to know the total number of records:
SELECT COUNT(*) FROM customers;
Use COUNT(column_name) to see how many records have actual data in a specific field:
SELECT COUNT(email) FROM customers;
If some customers don't have emails recorded (NULL values), COUNT(email) will return a smaller number than COUNT(*), showing you exactly how many customers do have emails on file.
Practical Analogy
Imagine a survey form. COUNT(*) tells you how many forms were submitted total. COUNT(phone_number) tells you how many people actually filled in their phone number—some might have left it blank.
Key Takeaway: Use COUNT(*) to count all rows in your query results, and COUNT(column_name) to count only rows with non-null values in that specific column—perfect for understanding data completeness.