Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What makes one of these queries faster?

Tags:

sql

sql-server

I have a sql query that I tried executing (below) that took 10 seconds to run, and since it was on a production environment I stopped it just to be sure there is no sql locking going on

SELECT TOP 1000000 *
  FROM Table T
  Where CONVERT(nvarchar(max), T.Data) like '%SearchPhrase%' --T.Data is initially XML

Now if I add an order by on creation time (which I do not believe is an index), it takes 2 seconds and is done.

SELECT TOP 1000000 *
  FROM Table T
  Where CONVERT(nvarchar(max), T.Data) like '%SearchPhrase%' --T.Data is initially XML
  order by T.CreatedOn asc

Now the kicker is that only about 3000 rows are returned, which tells me that even with the TOP 1000000 it isn't stopping short on which rows it's still going through all the rows.

I have a basic understanding of how SQL server works and how the query parsing works, but I'm just confused as to why the order by makes it so much faster in this situation.

The server being run is SQL server 2008 R2

like image 384
Dan Drews Avatar asked Jun 04 '13 13:06

Dan Drews


People also ask

What makes a query faster?

The way to make a query run faster is to reduce the number of calculations that the software (and therefore hardware) must perform. To do this, you'll need some understanding of how SQL actually makes calculations.

How do I make select queries faster?

Use only the correct number of columns you need When you code all queries with SELECT, you pull off more data than you need. So here's how to make the SELECT query faster: before doing a SELECT, make sure you have the correct number of columns against as many rows as you want. This will speed up your processes.

How do you make a query not faster?

You can use a left outer join, or a not exists clause. Both are quite generic SQL solutions (don't depend on a specific DB engine). I would say that the latter is a little bit more performant (not by much though).

Which query is faster in MySQL?

MySQL full-text search (FTS) is far much faster than queries using wildcard characters.


1 Answers

The additional sort operation is apparently enough in this case for SQL Server to use a parallel plan.

The slower one (without ORDER BY) is a serial plan whereas the faster one has a DegreeOfParallelism of 24 meaning that the work is being done by 24 threads rather than just a single one.

This explains the much reduced elapsed time despite the additional work required for the sort.

like image 119
Martin Smith Avatar answered Oct 13 '22 23:10

Martin Smith