wnajar wnajar - 1 year ago 107
MySQL Question

Fastest way to count number of rows in MySQL database in Laravel?

I can think of a couple ways to count the number of rows in a table with Laravel (version 3).

DB::query('SELECT COUNT(*) FROM threads;');

Are any of these notably faster than the others? Is there any one fastest way to run this query? Later on it's going to be part of an expression:
ceil(DB::table('threads')->count() / $threads_per_page);
and it's executed on every page load so it's good to be optimized.

Database/table is MySQL and the InnoDB engine.

Answer Source

MAX(ID) is not the same as counting rows, so that rules out two of five alternatives.

And then it is your task to actually do a performance comparison between the remaining three methods to get the count. I'd think that actually executing an SQL statement directly might remove plenty of unnecessary ORM-layer overhead and be actually faster, but this would be premature optimization unless proven by facts.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download