sqlsnowflake-cloud-data-platform

Enforcing specific join order


I am looking for a way to preserve a specific join order during query execution:

SELECT *
FROM tab1
JOIN tab2
  ON tab1.t2_id = tab2.id
JOIN tab3
  ON tab1.t3_id = tab3.id;

Effectively an equivalent of a query hint like:


Solution

  • Directed joins:

    The DIRECTED keyword specifies a directed join, which enforces the join order of the tables. The first, or left, table is scanned before the second, or right, table. For example, o1 INNER DIRECTED JOIN o2 scans the o1 table before the o2 table. Directed joins are useful in the following situations:

    • You are migrating workloads into Snowflake that have join order directives.
    • You want to improve performance by scanning join tables in a specific order.

    If the DIRECTED keyword is added, the join type — for example, INNER or OUTER — is required.

    SELECT *
    FROM tab1
    INNER DIRECTED JOIN tab2
      ON tab1.t2_id = tab2.id
    INNER DIRECTED JOIN tab3
      ON tab1.t3_id = tab3.id;