Hi Aron
Not completely sure, but I think it is due to the execution of the right function expressions. If you check the execution plan of both the statements, then the expressions are executed as following.
Let's take the second example: The execution plan shows that the right() function is interpreted as:
SUBSTR(CONCAT('00000', PADDED), LENGTH(CONCAT('00000', PADDED)) - 4)
Here the PADDED is executed first in the subquery and is has fixed length in both the CONCAT and LENGHT(CONCAT) operands of the SUBSTR.
The PADDED can have values which are single digit or 2 digits, so the SUBSTR is interpreted as example:
SUBSTR(CONCAT('00000', '33'), LENGTH(CONCAT('00000', '33')) - 4)
= SUBSTR(CONCAT('00000', '33'), 3)
= 00033
or
SUBSTR(CONCAT('00000', '5'), LENGTH(CONCAT('00000', '5')) - 4)
= SUBSTR(CONCAT('00000', '5'), 2)
= 00005
But in the first statement, the right expression is converted to:
SUBSTR(CONCAT('00000', TO_NVARCHAR(ROUND(RAND() * 100, 0))), LENGTH(CONCAT('00000', TO_NVARCHAR(ROUND(RAND() * 100, 0)))) - 4)
Here since there are 2 rand() functions, the value of the length could be vary. You can apply the similar logic and examples:
SUBSTR(CONCAT('00000', TO_NVARCHAR(ROUND(RAND() * 100, 0))), LENGTH(CONCAT('00000', TO_NVARCHAR(ROUND(RAND() * 100, 0)))) - 4)
= SUBSTR(CONCAT('00000', '33')), LENGTH(CONCAT('00000', '3')) - 4)
= SUBSTR('0000033', 2)
= 000033
or
SUBSTR(CONCAT('00000', TO_NVARCHAR(ROUND(RAND() * 100, 0))), LENGTH(CONCAT('00000', TO_NVARCHAR(ROUND(RAND() * 100, 0)))) - 4)
= SUBSTR(CONCAT('00000', '3')), LENGTH(CONCAT('00000', '33')) - 4)
= SUBSTR('000033', 3)
= 0033
Hence the execution depends up what random values are being populated at the runtime.
Hope I tried to explain it in some way..![]()
Regards,
Ravi