SQL
SQL COUNT() Function: Syntax, Usage, and Examples
The COUNT() function returns the number of rows that match a query. It’s one of the most frequently used aggregate functions in SQL, and it plays a vital role in reporting, data summaries, and analytics.
In an SQL database, COUNT helps with everyday data analysis across small tables and large datasets, giving you a quick tally of a number of records that meet your conditions.
Learn SQL on Mimo
How to Use COUNT in SQL
The basic syntax of COUNT can vary depending on what you're counting—rows, specific values, or distinct values. Here’s the general syntax:
SQL
SELECT COUNT(*) FROM table_name;
This counts all rows in the table, including those with NULL values. In a typical SELECT statement, COUNT pairs with a table in the FROM clause and optional filters in WHERE.
COUNT(*) vs COUNT(column)
COUNT(*): Counts all rows, regardless of null values.COUNT(column_name): Counts only non-null values in the specified column.
SQL
SELECT COUNT(email) FROM users;
This counts users who have a non-null email. Be mindful of data types—COUNT works across integers, text, and dates, but COUNT(column) skips NULL values in that specific type.
When to Use COUNT
The COUNT function is useful any time you need a tally:
- Count total records in a table
- Count non-null values in a specific column
- Count distinct values
- Count grouped data
- Validate results in subqueries or joins
- Track progress, do quick checks, and surface metrics for optimization
SELECT COUNT for Quick Audits
Quickly check table size:
SQL
SELECT COUNT(*) FROM customers;
This is commonly used to verify data loads, troubleshoot queries, or monitor data growth.
Using COUNT in Filtering
You can filter results using HAVING with COUNT:
SQL
SELECT country, COUNT(*) AS num_customers
FROM customers
GROUP BY country
HAVING COUNT(*) > 100;
This finds countries with more than 100 customers. The filter applies after grouping in the GROUP BY clause, and the condition appears in the HAVING clause.
Examples of COUNT
Example 1: COUNT Total Rows
SQL
SELECT COUNT(*) AS total_orders
FROM orders;
Returns the total number of rows in the orders table.
Example 2: COUNT Non-Null Values
SQL
SELECT COUNT(email) AS valid_emails
FROM users;
Counts users with a valid (non-null) email.
Example 3: COUNT DISTINCT
SQL
SELECT COUNT(DISTINCT country) AS unique_countries
FROM customers;
This COUNT DISTINCT query tells you how many different countries your customers come from. You can think of DISTINCT here as using the DISTINCT keyword inside COUNT to remove duplicates before tallying.
Example 4: Query Count by Group
SQL
SELECT status, COUNT(*) AS total
FROM support_tickets
GROUP BY status;
This breaks down ticket count by status—open, closed, pending, etc. The returned table is your result set after aggregation.
Example 5: COUNT of COUNT Pattern
In advanced reports, you might need a COUNT OF COUNT structure, using a subquery:
This counts how many departments have more than 50 employees.
Learn More About COUN
COUNT with WHERE Clause
You can combine COUNT with a WHERE clause to count rows matching specific conditions:
SQL
SELECT COUNT(*) AS late_orders
FROM orders
WHERE delivery_status = 'Late';
This counts only rows where the status is 'Late'.
COUNT in Joins
When using joins, be careful which table’s columns you count. For example:
SQL
SELECT c.name, COUNT(o.id) AS order_count
FROM customers c
LEFT JOIN orders o ON c.id = o.customer_id
GROUP BY c.name;
Using COUNT(o.id) avoids counting nulls when a customer has no orders.
COUNT UNIQUE Values
Another way to say sql count unique is to use COUNT(DISTINCT column):
SQL
SELECT COUNT(DISTINCT email) AS unique_emails
FROM newsletter_subscribers;
This avoids duplicate entries in the count.
Combining COUNT with Other Aggregates
You can use COUNT alongside SUM, AVG, or MAX:
SQL
SELECT department, COUNT(*) AS total_staff, AVG(salary) AS avg_salary
FROM employees
GROUP BY department;
This summarizes both headcount and average salary per department.
COUNT with CASE for Conditional Logic
You can use CASE statements to perform conditional counts:
SQL
SELECT
COUNT(CASE WHEN status = 'Open' THEN 1 END) AS open_tickets,
COUNT(CASE WHEN status = 'Closed' THEN 1 END) AS closed_tickets
FROM support_tickets;
This gives you multiple counts in one query, broken down by condition.
SQL Query Count Across Date Ranges
Often, you’ll count values over time to analyze trends:
SQL
SELECT
DATE(order_date) AS day,
COUNT(*) AS daily_orders
FROM orders
GROUP BY DATE(order_date)
ORDER BY day;
This turns row-level data into meaningful insights for visualization or reporting.
Using COUNT in Subqueries
In real-world queries, COUNT often appears inside subqueries. For example:
SQL
SELECT name
FROM products
WHERE (
SELECT COUNT(*)
FROM order_items
WHERE order_items.product_id = products.id
) > 100;
This finds products ordered more than 100 times.
COUNT in Common Table Expressions (CTEs)
CTEs make COUNT logic easier to read and extend:
SQL
WITH department_stats AS (
SELECT department_id, COUNT(*) AS employee_count
FROM employees
GROUP BY department_id
)
SELECT * FROM department_stats
WHERE employee_count > 20;
CTEs are useful for creating modular, readable SQL code.
COUNT and Performance
COUNT(*) can be fast or slow depending on the engine and table size. Indexes, partitions, and storage engines matter. Some databases like PostgreSQL or MySQL InnoDB perform a full scan for COUNT(*), while others like SQL Server can use metadata.
To improve performance:
- Use
WHEREclauses to limit data scanned - Avoid
COUNT(*)on joined views unless necessary - Use indexed columns in
COUNT(column)when possible
Alternatives to COUNT
In some cases, developers mistakenly use SELECT * to check if a table has data. Use COUNT(*) or EXISTS instead:
SQL
-- Less efficient
SELECT * FROM products;
-- Better for checking presence
SELECT COUNT(*) FROM products;
-- Even faster if you just need existence
SELECT EXISTS(SELECT 1 FROM products);
EXISTS returns faster in large tables if only presence is needed.
Quick Setup Example with CREATE TABLE
If you’re new and want a tiny sandbox, start with a simple schema using CREATE TABLE and then count rows:
SQL
CREATE TABLE signups (
id SERIAL PRIMARY KEY,
email TEXT NOT NULL,
plan TEXT
);
INSERT INTO signups (email, plan)
VALUES ('jordan@example.com', 'free'),
('devon@example.com', 'pro'),
('kai@example.com', NULL);
-- Count all rows in a classic SELECT
SELECT COUNT(*) AS total FROM signups;
-- Count distinct plans (skips NULLs)
SELECT COUNT(DISTINCT plan) AS plans
FROM signups;
Each query returns a result set with your counts. The structure is the same: a SELECT statement, a FROM clause, and optional grouping or filtering depending on the question you’re answering during data analysis.
Join 35M+ people learning for free on Mimo
4.8 out of 5 across 1M+ reviews
Check us out on Apple AppStore, Google Play Store, and Trustpilot