The difference in that in query 1, Orders.OrderID != null (or Orders.OrderId is not null) is being used to filter the rows in the Orders table and in query2, it is being used to filter the rows in the result set.
SQL Query: difference in condition in On clause and where clause
-
15-07-2023 - |
سؤال
I am trying to get the difference between below 2 queries
Query 1:
In which I have given condition 'Orders.OrderID != null' in on clause
SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
LEFT JOIN Orders
ON (Customers.CustomerID=Orders.CustomerID and Orders.OrderID is not null)
Query 2:
In which I have given condition 'Orders.OrderID != null' in where clause
SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
LEFT JOIN Orders
ON Customers.CustomerID=Orders.CustomerID where Orders.OrderID is not null
These 2 queries are generating difference results. Why? What is the execution flow for where clause and on condition clause?
P.S I am using the following link for testing of the queries http://www.w3schools.com/sql/trysql.asp?filename=trysql_select_join
المحلول
نصائح أخرى
Change the != NULL
to IS NOT NULL
Change the != NULL
to IS NOT NULL
and do not forget to place parentheses at ON
clause.
This way you tell the server that you want all conditions (inside parentheses) to be met when joining.
The Q2 in fact it the same as INNER JOIN Orders
.
The rows without peer are filtered out.
UPDATE
for the Q1 if the condition is false the row from Customers is included in results. for the Q2 the left joined rows are filtered out because hteir OrderId is null
The syntax of your queries look similar to T-Sql, except the comparison "!=". If you are using MSSQL Server, the proper way to test null values is OrderId is not null
.
Besides the uses of different operators, the behaviors of your queries are also driven by order of processing. The WHERE clause conditions are evaluated upon the results of all JOIN's. This is true for MSSQL. Because of that, putting conditions in WHERE clause has similar effects as if you do an INNER JOIN, except that you are wasting more resources.
The difference is that first query will output all rows from first table and only those rows from second table which match condition. That means that columns that belong to second table will be null
, but combined row would still exist in result.
In second case combined rows which have order ID null
will be removed.