Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is COUNT(*) indexed?

I want to know just for curiosity that, does Select Count(*) from SomeTableName also traverses all the rows of the database as that of Select * from SomeTableName?

Or is there any other count field available in database's metadata that updates itself each time a row is added or deleted? And that field is accessed by the former query.

Also I want to know that which of the both queries is faster and how much?

like image 931
Aishwarya Shiva Avatar asked Aug 13 '13 10:08

Aishwarya Shiva


People also ask

Does COUNT (*) Use index?

Index Used for COUNT(*) In most cases when we create a nonclustered index on few columns of SQL Server. Unless we create a nonclustered index with all the columns of the table, it is usually a much narrower index.

What does COUNT (*) mean in SQL?

COUNT(*) returns the number of rows in a specified table, and it preserves duplicate rows. It counts each row separately. This includes rows that contain null values.

Are COUNT (*) and COUNT () the same function?

As you've already learned, COUNT(*) will count all the rows in the table, including NULL values. On the other hand, COUNT(column name) will count all the rows in the specified column while excluding NULL values.

What is COUNT (*) used for?

The COUNT function counts the number of cells that contain numbers, and counts numbers within the list of arguments.


1 Answers

SELECT Count(*)
FROM   SomeTableName 

will always count all rows. Though (unlike SELECT *) it does not have to read all columns and can use the narrowest (non filtered) index available to do so.

Unlike MySQL (MyISAM engine) it does not retrieve the value from metadata.

A rowcount value is available in the metadata and can be retrieved from sys.partitions but this is never used for COUNT queries and isn't always accurate.

like image 150
Martin Smith Avatar answered Oct 14 '22 07:10

Martin Smith