I have a sql query that runs super fast, around one second, when not using variables, like:
WHERE id BETWEEN 5461094 and 5461097
But when I
It seems like this query is relating to a stored procedure, its execution plan will get compiled first time the proc is executed and then reused for subsequent executions.
Its possible that the compiled plan is really bad for situations where firstid is really close to lastid, however its really good when the values are far apart.
Try enabling the WITH RECOMPILE option on your stored proc. If it resolves the issue and you are happy with the proc being recompiled every time its executed (you will get a performance hit) leave it there. If you are still unhappy with the performance consider re-architecting the proc so it does not need the recompilation.