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

reinisk22's avatar

How to optimize my SQL query

Hey,

I got this query, where I basically need to check how many IDs haven't been assigned for a certain strategy:

->where('strategy', (string) $strategy)
            ->whereNotNull('assigned_at')
            ->count();

raw SQL:

select count(*) as aggregate from `external_ids` where `strategy` = 'very long string' and `assigned_at` is not null;

And the issue is, the query seems to work pretty slow because of the count. Could someone please help me optimize this?

Table info: https://imgur.com/a/YIxaF3b

0 likes
9 replies
automica's avatar

@reinisk22 is it slow in production or slow in development?

if you run the query directly in MySQL does it take the same amount of time to run it?

I've seen reports of slow queries and it very often comes down to issues with local windows development environments.

switching to use homestead or docker usually improves this.

neilstee's avatar

@reinisk22 have you tried using indexes in MySQL? This can improve your query performance significantly.

Resources: https://laracasts.com/series/mysql-database-design/episodes/13 https://www.youtube.com/watch?v=HubezKbFL7E

Basically, I think you need to index strategy and assigned_at column and also another column for your count() function because that needs to be index as well. probably the best is to select count(id) ... instead of select count(*) so you can index your id column (assuming you have id column in your table)

reinisk22's avatar

@automica It's slow in production. I don't fully understand why my manager wants to optimize this tho, I ran the query against prod DB and it took about 2.5 seconds which isn't that bad and the query isn't being run very often.

reinisk22's avatar

@neilstee I just checked the DB tables. It seems like they are indexed, but then again, I don't really know much about it, will take a look at the suggested videos, thanks!

Sinnbeck's avatar

Some images of the table setup might help us get some ideas as to how it is set up, and how you can improve it.

neilstee's avatar

@reinisk22 can you EXPLAIN the query?

explain select count(*) as aggregate from `external_ids` where `strategy` = 'very long string' and `assigned_at` is not null;
newbie360's avatar

what about

->whereNotNull('assigned_at')
	->where('strategy', (string) $strategy)
        ->count('id');

Please or to participate in this conversation.