Skip to content

Speed up count query by removing aggregate functions from SELECT #3159

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Seb33300 opened this issue Jul 11, 2024 · 2 comments
Closed

Speed up count query by removing aggregate functions from SELECT #3159

Seb33300 opened this issue Jul 11, 2024 · 2 comments

Comments

@Seb33300
Copy link
Contributor

Summary of problem

I have a query looking like this:

$companies = Company::select([
            'companies.*',
            DB::raw('SELECT COUNT(*) FROM orders WHERE orders.company_id = companies.id'),
        ])
        ...

This generates 2 queries:

  • first query to count the number of rows (count_row_table)
  • 2nd query to select the current page results

This works well, but the count_row_table query is taking a while because we have a lot of companies, and the query includes the aggregation function to count orders, which is useless in the count_row_table query:

SELECT 
    COUNT(*) AS aggregate
FROM
    (SELECT companies.*, (SELECT COUNT(*) FROM orders WHERE orders.company_id = companies.id) FROM companies) count_row_table

If I remove it from the select, the query becomes very fast again:

SELECT 
    COUNT(*) AS aggregate
FROM
    (SELECT companies.* FROM companies) count_row_table

Is there any way to remove it from the count_row_table query?

@yajra
Copy link
Owner

yajra commented Jul 13, 2024

What version are you using? There was a recent patch #3135 similar to this concern.

@Seb33300
Copy link
Contributor Author

Thanks for your reply.
I updated to the latest version and tried again but it did not fix my issue.

However, while reading the comments of the PR, I found the ignoreSelectsInCountQuery() method I can use to ignore the selects in the count query and that's exactly what I was looking for.
Using that method fixed my issue.

@github-actions github-actions bot locked and limited conversation to collaborators Jul 30, 2024
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants