[Solved] SQL Slow in code not SSMS
Looking to automatically optimize YOUR SQL query? Start for free.

EverSQL Database Performance Knowledge Base

SQL Slow in code not SSMS

I am running into issues working with a very large table from C# .Net 4.0.

For reference the table has ~120 Million rows.

I can't do even a simple query like

SELECT TOP(50) * 
FROM TableName 
WHERE CreatedOn < '2015-06-01';  

From code it will timeout (Default setting - 15 seconds I believe), but in SSMS it is instant.

There is an index on the column in the WHERE clause. I have also tried explicitly casting the string to a DateTime, and using a DateTime parameter instead of a literal value.

I tried a different query that filters by the PK (bigint, identity, clustered index) If I do something like "Where TableRowID = 1" it works fine from code, but if I try to use "<" or "<=" instead it will timeout (returns instantly in SSMS), regardless of how many rows are turned.

The execution plans are very simple and are exactly the same. I have tried changing ARITHABORT but that has had no effect. I tried having the Application connect with my own account (SSPI) instead of its own credentials with no effect.

I have been researching this issue for a few days, but everything I have found blames different execution plans.

Does anyone have any idea what could be causing this issue?

The .Net code looks like this:

private DataSet ExecuteQuery(string query, string db, List<SqlParameter> parms = null)
{
    string connectionString = ConfigurationManager.ConnectionStrings[db].ToString();
    SqlConnection con = new SqlConnection(connectionString.Trim());
    SqlDataAdapter sqlDataAdapter = new SqlDataAdapter();
    try
    {
        con.Open();
        DataSet ds = new DataSet();
        sqlDataAdapter.SelectCommand = new SqlCommand(query, con);
        sqlDataAdapter.SelectCommand.CommandType = CommandType.Text;

        if (parms != null)
        {
            foreach (SqlParameter p in parms)
            {
                sqlDataAdapter.SelectCommand.Parameters.Add(p);
            }
        }

        sqlDataAdapter.Fill(ds);

        if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
        {
            return ds;
        }

        return null;
    }
    finally
    {
        if (sqlDataAdapter != null)
            sqlDataAdapter.Dispose();
        if (con != null)
            con.Dispose();
    }
}

The error message I get in .Net is the standard timeout message:

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

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 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.
  2. Create Optimal Indexes (modified query below): The recommended indexes are an integral part of this optimization effort and should be created before testing the execution duration of the optimized query.
Optimal indexes for this query:
ALTER TABLE `TableName` ADD INDEX `tablename_idx_createdon` (`CreatedOn`);
The optimized query:
SELECT
        TOP (50) * 
    FROM
        TableName 
    WHERE
        TableName.CreatedOn < '2015-06-01'

Related Articles



* original question posted on StackOverflow here.