Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is count(indexed column) faster than count(*)? [duplicate]

Tags:

sql

sql-server

Possible Duplicate:
Performance of COUNT SQL function

Hi all, I've very large tables and I need to know number of records in each , My question is does it reduce the run time if I run :

select count(indexed column like my PK) from tbTest

instead of

select count(*) from tbTest
like image 998
Asha Avatar asked Jul 01 '10 15:07

Asha


People also ask

Is Count * slower than count column?

Don't let the asterisk (*) make you think it has the same use as in SELECT * statement. No, COUNT(*) will not go through the whole table before returning the number of rows, making itself slower than COUNT(1) .

Is Count column faster than count *?

SQL COUNT Syntax:Count(*) is considerably faster than Count([Column Name]). If we use the following example table, we can demonstrate the use of the COUNT function. This will return the result of: 5 records. This will return the result of: 4 records.

Does indexing speed up sorting?

Using the indexes can improve the performance of the sorting operation because the indexes create an ordered structure of the table rows so that the storage engine can fetch the table rows in a pre-ordered manner using the index structure.

How do you speed up a count query?

So to make SELECT COUNT(*) queries fast, here's what to do:Get on any version that supports batch mode on columnstore indexes, and put a columnstore index on the table – although your experiences are going to vary dramatically depending on the kind of query you have.


2 Answers

see Performance of COUNT SQL function

The important thing to note is they are not equivalent

like image 165
Mike M. Avatar answered Oct 27 '22 23:10

Mike M.


Since the question is whether or not there is a performance difference, it would depend on the index. When you do COUNT(*), it will use the PK column(s) to determine the number of rows. If you do not have any indexes besides a clustered index on the PK column(s), it will scan the leaf nodes on the clustered index. That's probably a lot of pages. If you have a non clustered index that is skinnier than the clustered index, it will choose that instead, resulting in less reads.

So, if the column you select is contained in the smallest possible non-clustered index on the table, the SQL query optimizer will choose that for both count() (if you have a clustered ix that is the PK) and count(indexed_column). If you choose a count(indexed_col) that is only contained in a wide index, then the count() will be faster if your PK is a clustered index. The reason this works is that there is a pointer to the clustered index in all non-clustered indexes and SQL Server can figure out the number of rows based on that non-clustered index.

So, as usual in SQL Server, it depends. Do a showplan and compare the queries to each other.

like image 26
Anon246 Avatar answered Oct 27 '22 21:10

Anon246