Home > Database > Mysql Tutorial > SQL JOIN: WHERE vs. ON: What's the Key Difference in Filtering Joined Data?

SQL JOIN: WHERE vs. ON: What's the Key Difference in Filtering Joined Data?

Susan Sarandon
Release: 2025-01-23 02:49:11
Original
790 people have browsed it

SQL JOIN: WHERE vs. ON: What's the Key Difference in Filtering Joined Data?

SQL JOIN: Understanding WHERE and ON Clauses

Mastering SQL JOINs requires a clear understanding of the WHERE and ON clauses. While sometimes interchangeable, their functions differ significantly.

WHERE Clause: Post-Join Filtering

The WHERE clause filters the results of a join. Consider this example:

SELECT *
FROM Orders
LEFT JOIN OrderLines ON OrderLines.OrderID = Orders.ID
WHERE Orders.ID = 12345;
Copy after login

Here, the WHERE clause filters the output, showing only rows where Orders.ID is 12345. This applies after the LEFT JOIN has combined data from Orders and OrderLines.

ON Clause: Join Condition Definition

The ON clause defines the join condition itself. Observe:

SELECT *
FROM Orders
LEFT JOIN OrderLines ON OrderLines.OrderID = Orders.ID AND Orders.ID = 12345;
Copy after login

The ON clause dictates that only rows where OrderLines.OrderID matches Orders.ID and Orders.ID equals 12345 will be included in the join. This filtering happens during the join process.

Key Semantic Distinction

Although WHERE and ON might yield similar results with INNER JOINs, their semantic roles are distinct. WHERE filters the final joined dataset, while ON determines which rows are included in the join operation.

The above is the detailed content of SQL JOIN: WHERE vs. ON: What's the Key Difference in Filtering Joined Data?. For more information, please follow other related articles on the PHP Chinese website!

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