Skip to main content
When joining datasets on multiple possible keys, you might be tempted to use OR in your JOIN condition. This pattern prevents the query planner from optimizing the join, often causing queries to run for hours instead of seconds.
Using OR in JOIN conditions can make queries 100x slower or more. Always restructure OR conditions into single-key joins using the techniques in this guide.

The anti-pattern

This query attempts to match records where either user_id or email matches:
While logically correct, this pattern prevents the query planner from using efficient join algorithms. The planner cannot build a hash table or use indexes effectively when it must evaluate two conditions with OR.

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

  1. Combine keys into an array on each side of the join
  2. UNNEST the arrays to create one row per potential key
  3. JOIN on the single key column using standard equality

Example

This query:
  • Creates arrays containing both possible join keys
  • Uses UNNEST to expand each row into multiple rows (one per key)
  • Joins on a single key column, which the planner can optimize efficiently
  • Uses SELECT DISTINCT to remove duplicate matches
The UNNEST approach works well when you have more than two possible join keys or when the keys are already stored as arrays.

Solution 2: Using UNION

For simple cases with exactly two join conditions, UNION provides a cleaner alternative:
This approach:
  • 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

Both approaches transform the problematic OR condition into single-key joins that the query planner can optimize using hash joins or indexes.
To understand why OR conditions cause these performance problems, see Understanding JOIN Performance.

Understanding JOIN Performance

Learn why OR in JOINs prevents optimization

Query Optimization

More techniques for writing efficient queries

Joining Datasets

Fundamentals of combining data from multiple datasets

NQL Functions

Reference for UNNEST and other NQL functions