[Solved] Why does the SELECT command run faster when WHERE is included?

EverSQL Database Performance Knowledge Base

Why does the SELECT command run faster when WHERE is included?

Database type:

In SQL Server Management Studio 2012, I run this query:

SELECT * FROM Contacts

This query successfully executes in approximately 44 seconds.

SELECT * FROM Contacts WHERE FirsttName = 'David"

This query successfully executes in approximately 0 seconds. So I guess my question is what is happening that causes these query times to be so different. From my admittedly naive perspective, I would think that in both cases all table rows would need to be surveyed to check if FirstName is equal to 'David', and that the condition should not have that large of an effect. In reality, I assumed that the query would take a little longer, because of the additional check.

Another example is:

SELECT * FROM Jobs

successfully executes in approximately 25 seconds.

SELECT * FROM Jobs WHERE JobName = "Sales"

successfully executes in approximately 0 seconds.

This is not a life-threatening/blocking/oh my god why can't I solve this problem issue. Just something that makes me wonder.

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.
The optimized query:
SELECT
        * 
    FROM
        Contacts

Related Articles



* original question posted on StackOverflow here.