A
A
Alex2021-09-05 03:30:51
Laravel
Alex, 2021-09-05 03:30:51

Which way to count rows is faster and consumes less SQL or PHP resources?

There are records with two field values ​​stat = 1 and 2.

DB::table('table')->select(
            DB::raw('`stat`, count(`stat`) as `count`')
        )->where('tid','=',$tid)->groupBy('stat')->get();

This query counts records. How many entries have stat=1 and how many have stat=2.
There is also an option to request through the model all records with the desired "tid" ( Model::where('tid',$tid)->get() ) and get them counted by sorting through PHP.
Does anyone have any information about which way will be faster and less resource intensive?

p\s\ there is no possibility to check on large volumes, therefore it is interesting to listen to those who used the methods in practice or perhaps found comparative tests somewhere

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
FernandoErrNando, 2021-09-05
@alexjet73

In such cases, such calculations are always shifted to the database, for 1 request you get an answer and return it as a result.
If you try to get records for counting in PHP, then on large selections there is a high probability of getting too large an array of data that will not fit in the memory allocated for PHP, not to mention the data iteration time.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question