Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how does sql count work?

Tags:

I would like to understand how exactly does sql count work. Is it a whole table scan that happens or is it some property of the table that is read. However I feel a table scan would be an overhead in case of huge tables with lots of records.

like image 868
ria Avatar asked Jun 15 '10 12:06

ria


People also ask

What is the use of COUNT () and COUNT (*) in SQL?

COUNT() With NULL ValuesSELECT COUNT(*) returns the count of all records in the result set regardless of NULL values. SELECT COUNT(attribute) returns the count of records containing non-NULL values of the specified column.


2 Answers

In general either a table or index scan is performed. This is chiefly because in a MVCC-supporting engine, different transactions could see different rows, so there is no single "row count" which is simultaneously correct for everyone.

Likewise, if you have a WHERE clause, then the where condition could be different for different clients, so they see different numbers.

If you need to do a lot of counts of large tables, consider storing your own counters in a different table. Exactly how you do this is entirely application specific.

like image 145
MarkR Avatar answered Oct 20 '22 20:10

MarkR


This will depend very much on which SQL implementation you are using (MS SQL Server, MySQL, Oracle, PostgreSQL etc), and how clever its optimiser is.

It may also depend on the query. For example, with something like

SELECT COUNT(primary_key) FROM table;

the optimiser may realise that there is no need to scan the table (since there is no filtering with WHERE and no possibility that any values are NULL) and just return the size of the table. With a more complicated query (where there is filtering, or the possibility of NULLs), the database may have to scan the table, or it may be able to do some optimisation with the use of an index.

like image 30
psmears Avatar answered Oct 20 '22 19:10

psmears