The anti-pattern
This query attempts to match records where eitheruser_id or email matches:
Solution 1: Array flattening with UNNEST
The recommended approach is to combine your join keys into an array, flatten it with UNNEST, and then join on a single key column.How it works
- Combine keys into an array on each side of the join
- UNNEST the arrays to create one row per potential key
- JOIN on the single key column using standard equality
Example
- Creates arrays containing both possible join keys
- Uses UNNEST to expand each row into multiple rows (one per key)
- Joins on a single
keycolumn, which the planner can optimize efficiently - Uses
SELECT DISTINCTto remove duplicate matches
Solution 2: Using UNION
For simple cases with exactly two join conditions, UNION provides a cleaner alternative:- Runs two optimized single-key joins separately
- Combines the results and automatically removes duplicates with UNION
- May be easier to read for simple two-condition cases
Use
UNION ALL instead of UNION if you want to keep duplicates, but be aware this may produce unexpected results when both conditions match the same record.Choosing the right approach
| Approach | Best for | Trade-offs |
|---|---|---|
| UNNEST | Multiple keys, complex queries, keys already in arrays | Requires explicit DISTINCT, slightly more complex syntax |
| UNION | Exactly two conditions, readability is priority | Repeats query logic, harder to maintain with many conditions |
To understand why OR conditions cause these performance problems, see Understanding JOIN Performance.

