Count(*) vs Count(1) in SQL Server
Last Updated :
27 Sep, 2024
In SQL Server, the COUNT()
function is used to return the number of rows in a query result. There are different ways to use the COUNT()
function such as COUNT(*)
and COUNT(1)
. Although they produce the same result, there are subtle differences in how they work internally.
In this article, we will try to understand the difference between Count(*) vs Count(1) in SQL Server.
COUNT() Function in SQL
The COUNT()
function in SQL is a powerful tool used to count the number of rows that meet a specified condition in a query. It plays a crucial role in tasks such as aggregation, filtering, and data analysis. There are two primary variations of the COUNT()
function:
- COUNT(*): Counts all rows, including those with
NULL
values.
- COUNT(1): Counts all rows as well, but does not evaluate any column's
NULL
values since 1
is a constant.
1. COUNT(*)
It counts every row in the table, regardless of whether the row contains NULL
values or not. This is the most commonly used form of COUNT( )
.
Syntax:
SELECT COUNT(*) FROM table_name;
Explanation: When you use COUNT(*)
, SQL Server evaluates all rows and does not reference any specific column. It scans the entire table or the subset defined by a WHERE
clause.
2. COUNT(1)
The
COUNT(1)
also counts all rows in the table, just like COUNT(*)
, and ignores any NULL
values. Since 1
is a constant and not associated with any column, it does not check for NULL
s.
Syntax:
SELECT COUNT(1) FROM table_name;
Explanation: When using COUNT(1)
, SQL Server evaluates each row as "true" because 1
is always a non-null constant. It doesn't reference any specific column, so it doesn't need to inspect the actual data.
Example: Employees Table
The provided SQL queries demonstrate how different counting functions can yield varying results when dealing with NULL
values in the Employees table.
COUNT(*)
counts all rows in the table, including those with NULL
values resulting in a total of 4 rows.
COUNT(EmployeeName)
only counts the rows where the EmployeeName
column is not NULL
, which results in 2 rows.
This illustrates how COUNT
specifically excludes NULL
entries while COUNT(*)
includes all rows regardless of their contents.
Query:
-- Create Employees table
CREATE TABLE Employees (
EmployeeID INT PRIMARY KEY,
EmployeeName VARCHAR(100),
DepartmentID INT
);
-- Insert sample data with NULL values
INSERT INTO Employees (EmployeeID, EmployeeName, DepartmentID)
VALUES
(101, 'John Doe', 1),
(102, NULL, 2),
(103, 'Sam Green', 3),
(104, NULL, 4);
-- Using COUNT(*): Counts all rows, including rows with NULL values
SELECT COUNT(*) AS TotalRows FROM Employees;
-- Using COUNT(EmployeeName): Counts only rows where EmployeeName is NOT NULL
SELECT COUNT(EmployeeName) AS NonNullNames FROM Employees;
Output:
Explanation:
COUNT(*)
counts all rows, including rows with NULL
values.
COUNT(EmployeeName)
counts only rows where EmployeeName
is not NULL
. Thus, COUNT(EmployeeName)
produces a different result by excluding rows with NULL
in the EmployeeName
column.
Difference Between COUNT(*) and COUNT(1)
Feature | COUNT(*) | COUNT(1) |
---|
What is counted? | Counts all rows, regardless of column values, including NULL . | Counts all rows, using 1 as a constant, independent of column values. |
Checks for NULL values? | No (ignores column-specific NULL values). | No (since 1 is a constant, it doesn’t check columns). |
Performance difference | No significant difference in modern SQL Server. | No significant difference in modern SQL Server. |
Intuition | Explicitly indicates counting all rows. | Uses a constant value, which can be less intuitive. |
Execution Plan | Both have the same execution plan in modern SQL Server. | Both have the same execution plan in modern SQL Server. |
Use Case | Typically preferred as it clearly counts all rows. | Often seen in legacy code but performs similarly to COUNT(*) . |
Conclusion
Both COUNT(*)
and COUNT(1)
return the same result and perform similarly in modern SQL Server environments, as the SQL optimizer treats them equally. Historically COUNT(1)
was sometimes thought to be faster, but there is no significant performance difference in recent versions of SQL Server. Most developers prefer COUNT(*)
because it is more intuitive and clearly signifies counting all rows in a table.
Similar Reads
COUNT() Function in SQL Server
The COUNT() function in SQL Server is a fundamental aggregate function used to determine the number of rows that match a specific condition. Counting rows provides valuable insights into data sets such as the total number of records, distinct values, or records meeting certain criteria. In this arti
3 min read
SUM() Function in SQL Server
The SUM() function in SQL Server is an essential aggregate function used to calculate the total sum of values in a numeric column. It aggregates data by summing up all values in the specified column for the rows that match the criteria of the query. In this article, We will learn about SUM() Functio
3 min read
How to Count Based on Condition in SQL Server?
In SQL Server, the COUNT() function is also utilized for tallying the number of records within a table. This article intends to explore the query, focusing on incorporating conditions into the COUNT() function in SQL Server. The COUNT() function in SQL Server is commonly utilized to count all record
4 min read
SIGN() Function in SQL Server
In SQL Server, the SIGN() function is a mathematical function used to determine the sign of a given numeric expression. This function is particularly useful when we want to evaluate whether a number is positive, negative or zero. In this article, We will learn about SIGN() Function in SQL Server in
3 min read
GROUPING ID Function in SQL Server
SQL Server is a Relational Database Management System that is used to create and manipulate the database. It provides advanced security measures like encryption, access control, and auditing to protect sensitive data from unauthorized access. It Supports a wide range of data types, including structu
6 min read
Group By Vs Distinct Difference In SQL Server
Distinct is a relational database management system. SQL Server offers a wide range of features and tools that handle different needs, from small-scale applications to large-scale application solutions. GROUP BY has performance features, especially when dealing with large datasets and complex aggreg
5 min read
SQL Server FULL OUTER JOIN
Joins in SQL are used to retrieve data from multiple tables based on a related column (or common column) between them. In this article, we will learn how to use FULL OUTER JOIN, which returns all rows from both tables being joined. It combines the results of both LEFT OUTER JOIN and RIGHT OUTER JOIN
6 min read
SQL Count() Function
In the world of SQL, data analysis often requires us to get counts of rows or unique values. The COUNT() function is a powerful tool that helps us perform this task. Whether we are counting all rows in a table, counting rows based on a specific condition, or even counting unique values, the COUNT()
7 min read
SET ROWCOUNT Function in SQL Server
The ROWCOUNT Set Function causes the server to stop the query processing after the specified number of records is returned. One may limit the number of records returned by all subsequent SELECT statements within the session by using the keyword SET ROWCOUNT. Or we can say that this function causes T
2 min read
SQL Server POWER() Function
The POWER() function in SQL Server is a mathematical function that computes the result of raising a number (the base) to the power of another number (the exponent). It is a versatile function used for various calculations, such as squaring a number, computing roots or applying exponential growth in
4 min read