SQL count rows in a table
How do you count the total number of rows in a table using SQL? This is one of the most common queries for checking data size, validating records, or performing quick database analysis.
Counting rows in a table is one of the most common operations in SQL, especially when you need to understand the size of your dataset or validate how many records meet certain conditions. The standard way to achieve this is by using the COUNT() function.
For example, to count all rows in a table:
SELECT COUNT(*) AS total_rows
FROM Employees;
Here, COUNT(*) counts every row, including those with NULL values. This is useful when you want the total number of records in the table.
If you want to count only rows from a specific column (ignoring NULLs), you can write:
SELECT COUNT(EmployeeID) AS total_employees
FROM Employees;
This counts only the rows where EmployeeID is not NULL.
Key points to remember:
- COUNT(*) → Counts all rows in the table, regardless of column values.
- COUNT(column_name) → Counts only rows where that column is not NULL.
- COUNT(DISTINCT column_name) → Counts only unique values in a column.
Filtering rows → You can use WHERE to count specific records, e.g.:
SELECT COUNT(*)
FROM Employees
WHERE Department = 'HR';
In short, the COUNT() function in SQL is a simple yet powerful tool for data validation, reporting, and analytics. Whether you need the total number of rows or filtered counts, it provides flexibility to fit different scenarios.