SQL COUNT
COUNT is the most used aggregate function. COUNT(*) counts rows. COUNT(column) counts non-NULL values in that column. COUNT(DISTINCT column) counts unique non-NULL values.
On its own COUNT returns one number for the whole table; with GROUP BY it returns one count per group.
Syntax
SELECT COUNT(*) FROM table_name; SELECT COUNT(DISTINCT column) FROM table_name;
Try it yourself
Run the example below on a real PostgreSQL database, then change it and run it again. Nothing to install, no sign-up.
count.sql · PostgreSQL
Loading editor…
Examples
1. Count rows
SELECT COUNT(*) FROM customers;
Number of customers.
2. Count non-NULL values
SELECT COUNT(email) FROM customers;
Customers who have an email.
3. Count with a filter
SELECT COUNT(*) FROM orders WHERE status = 'cancelled';
Cancelled orders.
Common mistakes
- Using COUNT(column) when you mean COUNT(*), and silently skipping NULL rows.
Practice: test yourself
This challenge is from our interactive course. Write the query and press Check answer.
Challenge · 20 pts
How many different countries do our customers come from?
challenge.sql · PostgreSQL
Loading editor…
FAQ
Is COUNT(1) faster than COUNT(*)?
No. In PostgreSQL they perform the same; COUNT(*) is the clearest.
Learn SQL step by step
65 hands-on exercises, streaks, a leaderboard and a certificate.