TechnicalEloquent performance

Eloquent performanceLesson 11 of 28

Use Unions to Run Queries Independently

If a subquery is treated as dependent, wrap it in a derived table.

2 min readIntermediateLesson

Eloquent performance11

The problem

Separate queries were fast. Can you get that speed in a single query?

The fix

Combine two simple queries with UNION, and wrap the union in a derived table so it runs on its own.

✕ Instead of this

$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

✓ Do this

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');
});

The benefit

As fast as separate queries (3.84 ms), but in a single query: 3 queries on the page instead of 6.

Results

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

Why it works

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.

Watch out

  • Both sides of a union must return the same columns (here just the user ID).
  • Derived tables need an alias ('matches').
  • newQuery() gives you a fresh query builder without importing the DB facade.

Frame from lesson 11

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.

Key takeaway

If a subquery is treated as dependent, wrap it in a derived table.

Check yourself

EXPLAIN shows DEPENDENT SUBQUERY. What does that tell you?

Reveal answer

✓ Answer

The subquery is being re-run for each outer row. Breaking the dependency (for example with a derived table) usually fixes it.