SQL – COUNT
Count the number of rows or non-null values in a result set using the COUNT() function.
Table of Contents
COUNT() answers the most frequent question in data analysis: how many? How many students enrolled? How many products are in stock? How many orders were placed this month? It returns the number of rows that match your query — and the subtle difference between COUNT(*) and COUNT(column_name) is one of SQL’s most important nuances.
COUNT(*) counts every row including those with NULL values. COUNT(score) counts only rows where score is not NULL. This distinction matters enormously when your data has gaps.
COUNT variations
COUNT(*) -- All rows
COUNT(score) -- Rows where score is NOT NULL
COUNT(DISTINCT city) -- Number of unique cities
Try It Yourself — Interactive SQL Editor
Edit the query below and click Run Query ▶ to see live results powered by SQLite running directly in your browser.
Key Points
- COUNT(*) counts all rows regardless of NULL
- COUNT(col) skips NULLs in that column
- COUNT(DISTINCT col) counts unique, non-null values
- COUNT is frequently the first aggregation applied in reporting
Pro Tip from CodesCompiler: The best way to learn SQL is to break things intentionally — modify the query above, change the WHERE conditions, try different columns. Every error teaches you something the docs cannot.
In the next lesson, we continue exploring SQL’s powerful feature set to build your database mastery.