1

If I have the following scenario, would Replace be evaluated a single time?

DECLARE @text nvarchar(32) = 'This is a test field'

SELECT textField FROM Table
WHERE Id = @idICareAbout AND textField = REPLACE(@text, ' ', '')

I would hope that it would, but I tend to be nervous about it and do this instead:

DECLARE @text nvarchar(32)
Select @text = REPLACE('This is a test field', ' ', '')

SELECT textField FROM Table
WHERE Id = @idICareAbout AND textField = @text

Of course replace here is just an example, and I'm sure this second variant is probably clearer and safer, but occasionally when I'm over optimizing, I think "What if I didn't have to do the replace at all, because the first part of the WHERE expression evaluates to false". Normally this would be such a micro-optimization it's silly to even think about but there have been a few times where the scenario is such that it may make a not miniscule difference. (Many more where clause parameters and maybe a bunch of HASHBYTES of parameters passed in.)

So I'm just curious how SQL server handles it.

user353gre3
  • 1,449
  • 1
  • 13
  • 20
Dean
  • 341
  • 2
  • 12

1 Answers1

4

SQL Server optimizer does constant folding, when possible. But is not a black-or-white issue, there are many shades of gray. See Compute Scalars, Expressions and Execution Plan Performance or Troubleshooting Poor Query Performance: Constant Folding and Expression Evaluation During Cardinality Estimation. You also need to read Conor vs. Runtime Constant Functions to get a grasp what is 'constant' in SQL to start with.

See http://rusanu.com/2009/09/13/on-sql-server-boolean-operator-short-circuit/ for an example when SQL Server does not do boolean short-circuit.

Glorfindel
  • 2,201
  • 5
  • 17
  • 26
Remus Rusanu
  • 51,846
  • 4
  • 95
  • 172