[Solved] ASP.NET / SQL Server - Timeout expired while searching
Looking to automatically optimize YOUR SQL query? Start for free.

EverSQL Database Performance Knowledge Base

ASP.NET / SQL Server - Timeout expired while searching

Database type:

We have a table called Purchases:

| PRSNumber   | ... | ... | ProjectCode |
| PRJCD-00001 |     |     | PRJCD       |
| PRJCD-00002 |     |     | PRJCD       |
| PRJCD-00003 |     |     | PRJCD       |
| PRJX2-00003 |     |     | PRJX2       |
| PRJX2-00003 |     |     | PRJX2       |

Note: ProjectCode is the prefix of PRSNumber.

Before, when there is no ProjectCode field in the table, our former developers use this query to search for purchases with specific supplier:

select * from Purchases where left(PRSNumber,5) = @ProjectCode

Yes, they concatenate the PRSNumber in order to obtain and compare the ProjectCode. Although, the code above works fine regardless of the table design.

But when I added a new field, the ProjectCode, and use this query:

select * from Purchases where ProjectCode = @ProjectCode

I receive this exception:

Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.

I can't believe, that the first query, which needs concatenation before the compare, is faster than the second one which has to do nothing but compare. Can you please tell me why is this happening?

Some information which might be helpful:


How to optimize this SQL query?

The following recommendations will help you in your SQL tuning process.
You'll find 3 sections below:

  1. Description of the steps you can take to speed up the query.
  2. The optimal indexes for this query, which you can copy and create in your database.
  3. An automatically re-written query you can copy and execute in your database.
The optimization process and recommendations:
  1. Avoid Calling Functions With Indexed Columns (query line: 7): When a function is used directly on an indexed column, the database's optimizer won’t be able to use the index. For example, if the column `PRSNumber` is indexed, the index won’t be used as it’s wrapped with the function `left`. If you can’t find an alternative condition that won’t use a function call, a possible solution is to store the required value in a new indexed column.
  2. Avoid Selecting Unnecessary Columns (query line: 2): Avoid selecting all columns with the '*' wildcard, unless you intend to use them all. Selecting redundant columns may result in unnecessary performance degradation.
The optimized query:
    left(Purchases.PRSNumber, 5) = @ProjectCode

Related Articles

* original question posted on StackOverflow here.