Separate queries were fast. Can you get that speed in a single query?
Search time
~450 ms3.84 ms
99% lower
union inside `where in` vs. wrapped in a derived table
Eloquent performanceLesson 11 of 28
If a subquery is treated as dependent, wrap it in a derived table.
2 min readIntermediateLesson
Separate queries were fast. Can you get that speed in a single query?
Combine two simple queries with UNION, and wrap the union in a derived table so it runs on its own.
$query->whereIn('id', function ($query) use ($term) {
$query->select('id')->from('users')
->where('first_name', 'like', $term)
->orWhere('last_name', 'like', $term)
->union(/* company-name query */);
});
// EXPLAIN: DEPENDENT UNION, re-run for every row
Same union, wrapped in a derived table (from(..., 'matches')):
$query->whereIn('id', function ($query) use ($term) {
$query->select('id')
->from(function ($query) use ($term) {
$query->select('id')->from('users')
->where('first_name', 'like', $term)
->orWhere('last_name', 'like', $term)
->union(
$query->newQuery()
->select('users.id')->from('users')
->join('companies', 'companies.id', '=', 'users.company_id')
->where('companies.name', 'like', $term)
);
}, 'matches');
});
As fast as separate queries (3.84 ms), but in a single query: 3 queries on the page instead of 6.
Search time
~450 ms3.84 ms
99% lower
union inside `where in` vs. wrapped in a derived table
Queries
63
50% lower
compared with lesson 10
A derived table is a subquery in FROM. The database builds it once, on its own, then the outer query just checks IDs against that list. Without the wrapper, EXPLAIN showed DEPENDENT UNION: it was re-run for every row.
'matches').newQuery() gives you a fresh query builder without importing the DB facade.
The union version of the scope: whereIn('id') wraps a derived table (from(..., 'matches')) containing the first/last-name query, combined with ->union($query->newQuery()...) for the company-name join.
If a subquery is treated as dependent, wrap it in a derived table.
EXPLAIN shows DEPENDENT SUBQUERY. What does that tell you?
✓ Answer
The subquery is being re-run for each outer row. Breaking the dependency (for example with a derived table) usually fixes it.