Improving whereHas performance #46646
-
TL;DR
where exists (select * from `posts` where `users`.`id` = `posts`.`user_id` and `title` = ?) #not very good query
where exists (select 1 from `posts` where `users`.`id` = `posts`.`user_id` and `title` = ?) # good query Hey everyone, Author::query()
->select('id', 'name')
->whereHas('posts', function ($query) {
$query->where('title', 'Awesome post');
})->toSql() this eloquent returns select `id`, `name` from `users` where exists (select * from `posts` where `users`.`id` = `posts`.`user_id` and `title` = ?) that means the database engine may have to fetch all columns of any matching rows, even though only the existence of the rows is important. This can result in unnecessary overhead and slower query performance, especially for large tables or complex queries. we can optimize the query by selecting I have refactored the logic behind the subquery to get the optimized query and tested it locally select `id`, `name` from `users` where exists (select 1 from `posts` where `users`.`id` = `posts`.`user_id` and `title` = ?) would you like me to create a pr for it, or is that how intentionally you wanted the subquery to be? please let me know, Thanks! |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments
-
looks great to me |
Beta Was this translation helpful? Give feedback.
-
MySQL EXISTS states:
Perhaps it can make sense in some other drivers, but I don't see any reason for DB to miss such an optimization. |
Beta Was this translation helpful? Give feedback.
-
Thank you for asking this. |
Beta Was this translation helpful? Give feedback.
MySQL EXISTS states:
Perhaps it can make sense in some other drivers, but I don't see any reason for DB to miss such an optimization.