Skip to content
Advertisement

Comparing count(*) with select for one result

I have a table tb_xyz having field1, field2 as indexed.

Now I have two queries:

and

Assuming both queries are written to just check if this condition is met at least once. Which of them is more optimal. I tried checking for their execution times, but results were mixed, for small data.

Advertisement

Answer

The first query (SELECT ... LIMIT 1) will perform better as it can stop scanning the table as soon as it finds a matching row while the COUNT(*) query will have to scan the entire table to compute its result. You may find that using EXISTS:

is even more efficient than the LIMIT query; looking at your execution plan (from EXPLAIN <query>) will let you know if there’s a difference between the two which might cause a performance difference.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement