Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is SELECT COUNT(*) expensive?

Do you think it's a good idea to count entries from a really big table (like 50K rows) on each page load?

SELECT COUNT(*) FROM table

Right now I have like 2000 rows and seems pretty fast, I don't see any delays in page load :)

But the table should reach up to 50K entries... And I'm curious how it will load then

(ps: this page which shows the row count is private, in a Admin interface, not public)

like image 779
Emma Avatar asked Jul 31 '11 17:07

Emma


People also ask

Which is better COUNT (*) or COUNT 1?

The simple answer is no – there is no difference at all. The COUNT(*) function counts the total rows in the table, including the NULL values. The semantics for COUNT(1) differ slightly; we'll discuss them later. However, the results for COUNT(*) and COUNT(1) are identical.

What is COUNT (*) used for?

COUNT(*) The COUNT(*) function returns the number of rows in a dataset using the SELECT statement. The function counts rows with NULL, duplicate, and non-NULL values.

What does SELECT 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.

What is the difference between SELECT * and SELECT COUNT (*)?

Select * Would return the entire table while Select Count(*) would return the number of rows.


1 Answers

COUNT(*) is optimized to return very quickly if the SELECT retrieves from one table, no other columns are retrieved, and there is no WHERE clause. For example:

mysql> SELECT COUNT(*) FROM student;

This optimization applies only to MyISAM tables only, because an exact row count is stored for this storage engine and can be accessed very quickly.

Source

As you said you use MyISAM and your query is for the whole table, it doesn't matter if its 1 or 100000 rows.

like image 92
Jacob Avatar answered Oct 29 '22 09:10

Jacob