Home > Database > Mysql Tutorial > Count(*) vs. Count(1) in SQL Server: Does One Really Perform Better?

Count(*) vs. Count(1) in SQL Server: Does One Really Perform Better?

Linda Hamilton
Release: 2025-01-23 18:44:13
Original
735 people have browsed it

Count(*) vs. Count(1) in SQL Server: Does One Really Perform Better?

*Performance difference between COUNT() and COUNT(1) in SQL Server: in-depth analysis**

There has long been a debate about the use of COUNT() and COUNT(1) in SQL Server. Although the goal of both queries is to count the number of rows in the table, some developers believe that COUNT(1) performs better than COUNT().

In-depth understanding of the differences between the two

The main difference between

COUNT() and COUNT(1) is the expression they count. COUNT() Counts the number of rows in a table, regardless of whether any particular column contains data. In contrast, COUNT(1) counts the number of occurrences of the literal "1" in the specified column.

Performance Analysis

According to Microsoft documentation and empirical testing, there is no significant performance difference between COUNT(*) and COUNT(1) in SQL Server. The optimizer recognizes that these two expressions evaluate to the same and optimizes the query accordingly.

Misunderstandings of traditional concepts

The notion that COUNT(1) performs better than COUNT(*) probably stems from earlier versions of SQL Server or other database systems where there was a real performance difference between the two. However, in modern versions of SQL Server, this optimization is obsolete.

Example

To prove the equivalence of COUNT(*) and COUNT(1), consider the following query:

SELECT COUNT(*) FROM dbo.table1;
Copy after login

This query will return the same results as the following query:

SELECT COUNT(1) FROM dbo.table1;
Copy after login

Conclusion

Although both COUNT(*) and COUNT(1) can be used to count rows in SQL Server, there is no performance advantage in using one over the other. Developers are advised to choose the expression that best meets the specific requirements of their query.

The above is the detailed content of Count(*) vs. Count(1) in SQL Server: Does One Really Perform Better?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template