SQL Count Rows

Galaxy Glossary

How do you count the number of rows in a table using SQL?

The COUNT function in SQL is used to count the number of rows in a table or a subset of rows that meet specific criteria. It's a fundamental aggregate function for data analysis.
Sign up for the latest in SQL knowledge from the Galaxy Team!
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.

Description

The `COUNT` function is a powerful tool in SQL for determining the number of rows in a table or a subset of rows. It's crucial for understanding the size of your data and for performing various analyses. Unlike other aggregate functions that ignore NULL values, `COUNT(*)` counts all rows, including those with NULL values in the specified columns. `COUNT(column)` counts only non-NULL values in the specified column. This distinction is important when dealing with potentially missing data. For example, if you're counting customers, `COUNT(*)` will give you the total number of customers, while `COUNT(customer_email)` will only count customers who have a valid email address. This flexibility allows you to tailor the count to your specific needs. In many cases, `COUNT(*)` is the preferred choice as it's generally faster and simpler. It's a fundamental building block for more complex queries, such as calculating percentages or determining the prevalence of specific data points.

Why SQL Count Rows is important

The `COUNT` function is essential for understanding the size and characteristics of your data. It's a fundamental building block for many data analysis tasks, from simple reporting to complex statistical calculations.

Example Usage


CREATE TABLE Names (
    name VARCHAR(50) COLLATE utf8mb4_general_ci
);

INSERT INTO Names (name) VALUES ('M��ller');
INSERT INTO Names (name) VALUES ('Mueller');

SELECT name FROM Names WHERE name = 'Mueller';
-- This query might return 'M��ller' depending on the default collation

SELECT name FROM Names WHERE name COLLATE utf8mb4_unicode_ci = 'Mueller';
-- This query will return 'M��ller' because it explicitly uses utf8mb4_unicode_ci collation

Common Mistakes

Want to learn about other SQL terms?