If a query contains a join with multiple join constraints, are the constraints evaluated in left to right order or does SQL Server decide the optimum way to evaluate them?
In hopes of clarifying, I’ll try to explain why I’m asking. Let’s say I have a table named Alpha and it has two columns in addition to a standard ID. The first column is named Generic1 and is a varchar(20). The second is named Type and is a smallint. If Type = 1 then the value of Generic1 will actually be the ID of a record in another table (lets call it Bravo). If Type = 2 then the value of Generic1 will be some plain text value.
I want to write the following query:
select * from Beta b
left outer join Alpha a on a.Type = 1 and a.Generic1 = b.ID
If I can safely assume that SQL Server will only attempt the comparison of a.Generic1 = b.ID AFTER it has compared a.Type = 1, then I don’t have to worry about cast/conversion errors. I would like the SQL to avoid using syntax that is only valid in SQL Server if possible.
I’m guessing that SQL Server evaluates them as it sees fit, so I’ll have to add a CAST to be safe.
Why do you have a mixed column like this? Sounds like there should be a FK relationship to
Bravowhich at the moment presumably you have no way of enforcing.Anyway assuming you are stuck with this schema no order of evaluation is guaranteed in SQL Server. You would need to do something like
(Though you might want to use a method specifically for integers instead though as
isnumericdoes not guarantee that a value will successfully cast toint)