We have a query that we're running on SQL Server 2008 in the Management Studio. I can't give the exact query details, but let's say it's equivalent to this:
SELECT *
FROM MyView a (nolock) INNER JOIN MyTable b (nolock)
ON a.id = b.id AND a.thedate > b.thedate
WHERE a.period_start < '1/1/2012'
AND a.invoice_status = 5
AND b.memo like '%something'
AND b.memo LIKE '%something else%'
This query runs relatively fast, returning 100 records in less than a second.
I then change the * in the select to explicitly list a few specific columns I want to see from each joined table. (Nothing fancy, just regular columns.) For example:
SELECT a.column1, a.column2, b.column1, b.column2
FROM MyView a (nolock) INNER JOIN MyTable b (nolock)
ON a.id = b.id AND a.thedate > b.thedate
WHERE a.period_start < '1/1/2012'
AND a.invoice_status = 5
AND b.memo like '%something'
AND b.memo LIKE '%something else%'
Suddenly the query is taking many, many minutes to execute.
Lastly, I run the same query, but I add the * back in, to the last position of the select column list, and the query is back to the same fast speeds! What gives? I'm looking at the estimated execution plans, and I see the faster version mentions a "Hash Match" early on in the query that I don't see in the slower version.
SELECT a.column1, a.column2, b.column1, b.column2, *
FROM MyView a (nolock) INNER JOIN MyTable b (nolock)
ON a.id = b.id AND a.thedate > b.thedate
WHERE a.period_start < '1/1/2012'
AND a.invoice_status = 5
AND b.memo like '%something'
AND b.memo LIKE '%something else%'
Is there a way to address this, or do we have to keep the asterisk in place?
*you are using all the fields from all the tables in the view. When usinga.c1, a.c2,you may only be using fields from a sub-set of the tables in the view. Are you able to see the contents of the view? And can you run a test selecting at least 1 field from every table referenced by the view? Finally, could you generate the actual execution plans for each, rather than the estimated plans? – MatBailie May 2 '12 at 0:21