Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does SQL Server even look at a table when joining on a variable that returns false?

If I join table A to table B like this...

select A.* from A 
left outer join B on A.Id = B.aId and @param = 'someValue'

and @param does not equal 'someValue', does SQL Server even attempt to match records from table B or is it smart enough to know the condition will never be true?

like image 529
adam0101 Avatar asked Dec 08 '09 00:12

adam0101


People also ask

Which of the following indicates a table being joined with itself?

SELF JOIN: As the name signifies, in SELF JOIN a table is joined to itself. That is, each row of the table is joined with itself and all other rows depending on some conditions. In other words we can say that it is a join between two copies of the same table.

How does SQL JOIN work?

SQL JOIN. A JOIN clause is used to combine rows from two or more tables, based on a related column between them. Notice that the "CustomerID" column in the "Orders" table refers to the "CustomerID" in the "Customers" table. The relationship between the two tables above is the "CustomerID" column.

Can we join table and view in SQL?

Yes, you can JOIN views with tables. You can use views just like tables in SELECTs. Special considerations apply in other operations. A view can be thought of as either a virtual table or a stored query.


1 Answers

  • As a general rule, SQL does not guarantee runtime boolean operator short-circuit.
  • The query plan would have to work for any value of @param because plans are reused between executions

So while in a particular context you may find that the when @param has a different value then the outer join table may never be probed, you should not rely on it for correctness. Note that probe means that actual values are searched for in the table. The metadata information will always be checked. For example you cannot cheat and ask for a join to a table that doesn't exists.

In particular, do not attempt to create a single query where there should be two different ones (one that joins, one that doesn't).

like image 58
Remus Rusanu Avatar answered Oct 11 '22 07:10

Remus Rusanu