I want to speed up the following query
There are two conditions in the WHERE clause (see below query for reference)
Currently, it takes about 60 seconds. However
Did you compare the execution plans with and without (@Query is NULL) ?
I would use this procedure only for searching for a specific book title and remove (@Query is NULL). When you want all book titles within a Row-Number-Range you can also use a view. When you execute a stored procedure and there is no execution plan in cache SQL Server will genereate one. Maybe the first caller uses @Query = 'ocean'. Every other call regardles of the parameter-values will use the same plan. When you call the proc with @Query = NULL SQL Server must read 700.000 Rows. But the execution plan and memory grants are based on the query for 'ocean'. So it will spill out to tempDb because there is not enough memory and the used Operators in the execution plan may not be optimal.