A Simple Guide to the COUNT Function in SQL

Advertisement

Jun 04, 2025 By Tessa Rodriguez

Most people don’t get excited about SQL functions, but if you've ever worked with data, you’ve probably leaned on the COUNT() function more than once. It's simple, dependable, and one of the first tools people learn in SQL. Whether you're checking how many users have signed up, how many orders have been placed, or how many records meet a specific condition, COUNT() provides quick answers.

What makes it more than just basic is its flexibility. You can count all rows, skip nulls, check for unique values, or combine them with other SQL features for more specific results. It's not just a function—it’s a go-to solution for making sense of raw numbers in everyday queries and reports.

What You Can Actually Do With the COUNT Function in SQL?

COUNT(*) – Count All Rows

This is the most common and direct use of COUNT(). When you write COUNT(*), you're asking SQL to count every row in a result set, regardless of what’s in the rows. Even if some columns have NULL values, they still get counted.

SELECT COUNT(*) FROM employees;

This tells you how many total entries are in the employee's table. It’s useful when you're interested in just the quantity, not the content.

COUNT(column_name) – Ignore NULL Values

To count solely the rows containing data in a particular column (not NULL), place the column name in COUNT().

SELECT COUNT(email) FROM users;

This counts how many users have an email address. If some entries have NULL in the email column, they won’t be included in the total. This is handy for checking data completeness.

COUNT(DISTINCT column_name) – Count Unique Non-NULL Values

When you want to count how many unique values exist in a column, COUNT(DISTINCT ...) does the job.

SELECT COUNT(DISTINCT department) FROM employees;

This tells you how many different departments there are on your employee's table. Like the previous example, NULLs are not counted.

COUNT with GROUP BY – Count per Category

Sometimes, you don't just want a single number—you want to see counts broken down by a category. This is where GROUP BY comes in.

SELECT department, COUNT(*) FROM employees GROUP BY department;

This shows how many employees are in each department. It’s one of the most useful combinations of COUNT() because it helps you understand distributions within your data.

COUNT with WHERE – Count Specific Rows

If you only want to count rows that meet certain conditions, use a WHERE clause.

SELECT COUNT(*) FROM orders WHERE status = 'shipped';

This only counts the orders that have a status of "shipped." It filters your results before counting. It’s good for getting numbers tied to business logic or performance metrics.

COUNT in JOIN Queries – Count Matching Records Across Tables

You can use COUNT() after joining multiple tables to see how many records match.

SELECT customers.name, COUNT(orders.id)

FROM customers

LEFT JOIN orders ON customers.id = orders.customer_id

GROUP BY customers.name;

This shows how many orders each customer has. If a customer has no orders, they’ll still appear (because of the LEFT JOIN) with a count of zero. It’s useful when you need a full picture, including the gaps.

COUNT in Subqueries – Count as a Column Value

Sometimes, you don't want to show just the count—you want to include it as part of a larger query.

SELECT name,

(SELECT COUNT(*) FROM orders WHERE orders.customer_id = customers.id) AS total_orders

FROM customers;

This gives a list of customers and shows the number of orders each one has placed. It works like a lookup for each row, embedding the result as a column. It can be slower on big datasets but is flexible for custom reports.

COUNT with HAVING – Filter Groups by Count

If you use GROUP BY, you might want to filter the results by how many items are in each group. You can’t use WHERE for this—use HAVING instead.

SELECT department, COUNT(*)

FROM employees

GROUP BY department

HAVING COUNT(*) > 10;

This lists departments that have more than ten employees. It’s how you apply conditions after the count has been calculated, which is especially helpful when looking for overrepresented or underrepresented groups.

COUNT with CASE – Conditional Counting in One Query

This method lets you count different conditions in the same query using CASE statements inside COUNT(). It’s helpful when you want multiple counts side by side without running multiple queries.

SELECT

COUNT(CASE WHEN status = 'pending' THEN 1 END) AS pending_count,

COUNT(CASE WHEN status = 'shipped' THEN 1 END) AS shipped_count,

COUNT(CASE WHEN status = 'cancelled' THEN 1 END) AS cancelled_count

FROM orders;

This gives you counts for each order status all at once. It’s efficient and keeps your reports cleaner when you need quick stats across categories.

COUNT with OVER() – Count Without Grouping

This use of COUNT() with the OVER() clause lets you get row counts while keeping all individual rows in your result. It works like a window function.

SELECT name, department,

COUNT(*) OVER (PARTITION BY department) AS department_count

FROM employees;

Each row still shows the employee’s name and department, but now it also includes the total number of people in that department—without collapsing rows. This is useful when you need row-level detail along with grouped totals. It’s often used in analytics dashboards or reports where you need both individual and summary data together.

Conclusion

The COUNT() function in SQL appears simple, but it has more depth than most people realize. Used effectively, it helps you understand your data without requiring complicated logic. Whether you're trying to measure activity, find missing information, or build out reports that give real insight, COUNT() is something you’ll use often. And the more you work with it in different contexts—joins, subqueries, conditions, groupings—the more useful it becomes. It's not just a row counter. It's a building block for understanding what’s happening in your data.

Advertisement

Recommended Updates

Basics Theory

Choosing Between Alpaca and Vicuna: Which LLM Performs Better

Curious about Vicuna vs Alpaca? This guide compares two open-source LLMs to help you choose the better fit for chat applications, instruction tasks, and real-world use

Technologies

What Benefits Do IBM AI Agents Bring to Businesses?

IBM AI agents boost efficiency and customer service by automating tasks and delivering fast, accurate support.

Basics Theory

A Practical Guide to Working with Audio Using Librosa

How to use Librosa for handling audio files with practical steps in loading, visualizing, and extracting features from audio data. Ideal for speech and music and audio analysis projects using Python

Technologies

Explore How Nvidia Maintains AI Dominance Despite Global Tariffs

Discover how Nvidia continues to lead global AI chip innovation despite rising tariffs and international trade pressures.

Applications

Run Llama 3.1 405B On Vertex AI Without Hassle Today

Need to deploy a 405B-parameter Llama on Vertex AI? Follow these steps for a smooth deployment on Google Cloud

Applications

Compact Brilliance: How Phi-2 Is Changing Language Model Design

How Phi-2 is changing the landscape of language models with compact brilliance, offering high performance without large-scale infrastructure or excessive parameter counts

Impact

Voices That Matter: 12 Data Science Leaders Worth Following in 2025

Discover the top data science leaders to follow in 2025. These voices—from educators to machine learning experts—shape how real-world AI and data projects are built and scaled

Applications

AI Image Enhancers That Actually Work: 10 Top Picks for 2025

Looking for the best AI image enhancers in 2025? Discover 10 top tools that improve image quality, sharpen details, and boost resolution with a single click

Applications

Metabase: The Open-Source BI Tool for Simple Data Analysis

How the open-source BI tool Metabase helps teams simplify data analysis and reporting through easy data visualization and analytics—without needing technical skills

Applications

Which AI Assistant Wins in 2025? Comparing ChatGPT and HuggingChat

Compare ChatGPT vs. HuggingChat to find out which AI chatbot works better for writing, coding, privacy, and hands-on control. Learn which one fits your real-world use

Technologies

Fast RAG on CPUs: Using Optimum Intel and Hugging Face Embeddings

How CPU Optimized Embeddings with Hugging Face Optimum Intel and fastRAG can run fast, low-cost RAG pipelines without GPUs. Build smarter AI systems using Intel Xeon CPUs

Applications

Google Launches Tools and Protocol for Building AI Agents

Google debuts new tools and an agent protocol to simplify the creation and management of AI-powered agents.