Home > Database > Mysql Tutorial > Does Join Order Matter in SQL Queries, Especially with Outer Joins?

Does Join Order Matter in SQL Queries, Especially with Outer Joins?

Susan Sarandon
Release: 2025-01-17 17:37:08
Original
985 people have browsed it

Does Join Order Matter in SQL Queries, Especially with Outer Joins?

SQL JOIN order: does it matter?

In SQL, the order of JOIN operations will affect the query results, especially when using outer joins.

INNER JOIN

For inner joins, a row in table A matches a row in table B exactly based on a certain condition, and the order of the joins does not affect the results. This is because inner joins are both commutative and associative. Therefore, queries A and B shown below will produce the same results:

<code class="language-sql">-- A (内连接)
SELECT *
FROM a INNER JOIN b ON <条件>
INNER JOIN c ON <条件>;

-- B (内连接)
SELECT *
FROM a INNER JOIN c ON <条件>
INNER JOIN b ON <条件>;</code>
Copy after login

OUTER JOIN

For outer joins (LEFT, RIGHT or FULL), the order of the joins is important. Unlike inner joins, outer joins are neither interchangeable nor combinable.

Commutative Law

Commutativity means that a LEFT JOIN b is the same as b LEFT JOIN a. However, this is not true for outer joins. For example, the following query:

<code class="language-sql">a LEFT JOIN b ON b.ab_id = a.ab_id</code>
Copy after login

Returns all rows in table a and the corresponding rows in table b, or NULL if there is no match in table b. Opposite query:

<code class="language-sql">b LEFT JOIN a ON a.ab_id = b.ab_id</code>
Copy after login

Returns all rows in table b and the corresponding rows in table a, or NULL if there is no match in table a. If table a and table b have different numbers of rows, the two queries will produce different results.

Associative Law

The associative law of

means that (a LEFT JOIN b) LEFT JOIN c is equivalent to a LEFT JOIN (b LEFT JOIN c). However, this is not true for outer joins either. Consider the following equivalent query:

<code class="language-sql">a LEFT JOIN b ON b.ab_id = a.ab_id
LEFT JOIN c ON c.ac_id = a.ac_id</code>
Copy after login

If the condition c.ac_id = a.ac_id contains a NULL comparison, the associativity law may not hold. In other words, if NULL values ​​are involved in the join condition, the order of the joins will affect the result.

The above is the detailed content of Does Join Order Matter in SQL Queries, Especially with Outer Joins?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template