COUNT(*), COUNT(col) & COUNT(DISTINCT)
Master the critical distinctions between COUNT(*), counting non-null column values, and counting unique values.
COUNT(*), COUNT(col) & COUNT(DISTINCT) is an essential topic in SQL and relational database engineering.
Overview
Building on foundational principles introduced in sql-aggregate-functions, mastering count(*), count(col) & count(distinct) provides the core mental model and practical query skills needed for production relational database engineering.
SELECT
COUNT(*) AS total_users,
COUNT(phone) AS users_with_phone, -- ignores NULLs!
COUNT(DISTINCT country) AS total_countries -- counts unique values!
FROM users;
Key Concepts
- Understand the fundamental syntax, conventions, and mental model.
- Avoid common beginner traps, data type mismatches, and performance pitfalls.
- Apply practical idioms directly in production applications.
[!TIP] Master this concept to build a rock-solid foundation. Next, proceed to sum-avg-functions.