Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between select count(*), count(0), count(100), count(Id) in SQL Server 2008?

What is the difference between following SQL Server 2008 statements?

SELECT COUNT(*) FROM dbo.Regular_Report

SELECT COUNT(0) FROM dbo.Regular_Report

SELECT COUNT(1) FROM dbo.Regular_Report

SELECT COUNT(100) FROM dbo.Regular_Report

SELECT COUNT(ID) FROM dbo.Regular_Report
like image 628
Mahesh Avatar asked Dec 17 '25 07:12

Mahesh


2 Answers

The first four are all identical - they count the total number of rows.

The last one counts the number of rows where ID is not null.

like image 176
Mark Byers Avatar answered Dec 19 '25 23:12

Mark Byers


count(id) will count the non-null values in the id field.

All the other will count the number of records.

(The ones with literal numbers instead of * will count all the records where that value is not null. Probably the query planner will recognise that the literal value will never be null for any record, and do the same as count(*) instead of actually counting the non-null values.)

like image 27
Guffa Avatar answered Dec 19 '25 23:12

Guffa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!