Why the Logical Processing Order of the SELECT statement is not followed?
Having the following query: DECLARE @t TABLE (ID UNIQUEIDENTIFIER, BegDate SMALLDATETIME, EndDate SMALLDATETIME) INSERT INTO @t SELECT NEWID(), '19000101', '20151124' -- This is to show you that nothing is really selected SELECT 'You will never see it' FROM @t r1 INNER JOIN @t r2 ON
r1.ID WHERE 1=1 AND r1.BegDate > r2.BegDate AND r1.EndDate <= r2.EndDate SELECT
r1.ID, r2.BegDate, DATEADD(DAY, -1, r1.BegDate) AS EndDate FROM @t r1 INNER JOIN @t r2 ON
r1.ID WHERE 1=1 AND r1.BegDate > r2.BegDate -- This guarantees that r1.BegDate is not minimal value AND r1.EndDate <= r2.EndDate You are getting > Msg 517, Level 16, State 2, Line 21 > Adding a value to a 'smalldatetime' > column caused an overflow. even though the query should not return any data. The questions is why the `SELECT` stuff is executed before the `FROM`, `JOIN` and `WHERE` stuff, as this is not the [Logical Processing Order of the SELECT statement]. If you change the `19000101` value to `19000102`, just to get the execution plan the SQL engine is building, you should see this: ![alt text] The `Compute Scalar` is actually the `DATEADD` function execution: ![alt text] So, the `DATEADD` function is executed and throws an error. :
https://msdn.microsoft.com/en-us/library/ms189499.aspx : /storage/temp/3073-x1.png : /storage/temp/3074-x2.png
Logical processing is not the same as physical execution. As the link states > Note that the actual physical execution of the statement is determined by the query processor and the order may vary from this list. If you Parse the query (Ctrl-F5) or get the Estimated Execution Plan (Ctrl-L), then you get no error.