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

rhand's avatar
Level 6

Why does select in query not speed things up?

When I use

$project = Project::select(['id', 'subdomain'])
            ->where([
            'subdomain' => $subdomain,
            'published' => true
            ])
            ->first();

instead of $project = Project::where('subdomain', $subdomain)->where('published', true)->first(); (causing select *... ) and I check things in debug bar the query execution does not seem to change much at all.

I know the localhost database is small so perhaps 1.8-2.2ms per query won't fluctuate much.. but still I expected more. Any ideas if my select usage approach to optimize here is the right one?

0 likes
11 replies
automica's avatar
automica
Best Answer
Level 54

It’s certainly cleaner to only get the columns you need, but on the query you are doing you won’t see much difference in performance (as you are finding out).

It your table had more columns in it, you might see a little more variation.

If you want to check performance, you could try seeding 10000 rows and then rerunning your tests.

2 likes
Tray2's avatar

I would also put an index on published if you haven't already.

2 likes
rhand's avatar
Level 6

Indexed several columns already. Not the published column. Will have to look into it. Indexing all or almost all in one table might not be efficient either. Not an expert yet by far though so open for all suggestions and appreciate yours yet again.

Tray2's avatar

You are correct that too many indexes might slow things down. However indexes that can only have two values will improve the speed, unless of course you don't have any unpublished posts,

1 like
rhand's avatar
Level 6

Thanks. Looking into using Cache as well. Just not sure who to tag request like the one I have yet. Once for trying to grab cache, if not load data and add to cache. But how to make the first query to do a $john = Cache::tags(['people', 'artists'])->get('John'); of sorts for this project query I am not certain of yet.

rhand's avatar
Level 6

Added

$project = Cache::remember("subdomain.{$subdomain}", now()->addHours(12), function () use ($subdomain) {
  return Project::select(['id', 'subdomain'])
      ->where([
      'subdomain' => $subdomain,
      'published' => true
      ])
      ->first();
  });

and it works well. Thanks a lot for @michaloravec . Making headway here!

NB Need to understand where use here comes from still. But looking into that.

lemmon's avatar

@rhand

use is bringing $subdomain into the scope of the closure.

1 like

Please or to participate in this conversation.