Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

madsem's avatar

Query Speed/Performance which one is faster:

Hey,

which one would deliver results fastest when querying lots of relationships:

->with([
         'tags' => function ($query) {
             $query->select('id', 'tag_label'); // use index
         }
     ])->distinct();

or simply:

->with('tags')

The difference I am seeing when running these with EXPLAIN in mysql is that the first one is using "Using where; Using index", while the second on is using the "Using where; Using join buffer (Block Nested Loop)"

I'm not sure if it would be best in general to always use a closure along with "with()" where you expect to query tons of relationships (like web analytics for example), or if that wouldn't increase performance?

What do you guys think?

0 likes
0 replies

Please or to participate in this conversation.