๐ What Youโll Learn
- What
COUNT()
does - Basic and advanced syntax
- Real-world examples
- How to use
COUNT()
withGROUP BY
andWHERE
๐ What Is COUNT?
The COUNT()
function returns the number of rows that match a specific condition.
It is commonly used to:
- Count all rows
- Count non-null values in a column
- Get totals for grouped data
๐งฑ Basic Syntax
Count all rows (including NULLs)
SELECT COUNT(*) FROM table_name;
Count non-null values in a column
SELECT COUNT(column_name) FROM table_name;
๐งช Example: Total Users
SELECT COUNT(*) AS total_users
FROM users;
๐งช Example: Count Users with Email
SELECT COUNT(email) AS users_with_email
FROM users;
โ This excludes rows where
NULL
.
๐ Example with GROUP BY
Count users per country
SELECT country, COUNT(*) AS user_count
FROM users
GROUP BY country;
๐ Example with WHERE
Count users from USA
SELECT COUNT(*) AS usa_users
FROM users
WHERE country = 'USA';
๐ Recap
COUNT(*)
counts all rows, including those withNULL
sCOUNT(column)
counts non-null values only- Combine with
GROUP BY
for grouped totals - Add
WHERE
to count conditionally