title: Why SQL Server go slow when using variables?
body: <p>I have a sql query that runs super fast, around one second, when not using variables, like:</p>
  
  <pre><code>WHERE id BETWEEN 5461094 and 5461097
  </code></pre>
  
  <p>But when I have:</p>
  
  <pre><code>declare @firstId int
  declare @lastId int
  
  set @firstId = 5461094
  set @lastId = 5461097
  
  ...
      WHERE id BETWEEN @firstId and @lastId
  </code></pre>
  
  <p>... the query runs really slow, finishing only after some minutes. Why does it happen? I need to use variables. Can I do any improvement to avoid this performance problems?</p>