So, we have a table, InventoryListItems, that has several columns. Because we’re going to be looking for rows at times based on a particlar column (g_list_id, a foreign key), we have that foreign key column placed into a non-clustered index we’ll call MYINDEX.
So when I search for data like this:
-- fake data for example
DECLARE @ListId uniqueidentifier
SELECT @ListId = '7BCD0E9F-28D9-4F40-BD67-803005179B04'
SELECT *
FROM [dbo].[InventoryListItems]
WHERE [g_list_id] = @ListId
I expected that it would use the MYINDEX index to find just the needed rows, and then look up the information in those rows. So not as good as just finding everything we need in the index itself, but still a big win over doing a full scan of the table.
But instead it seems that I’m still getting a clustered index scan. I can’t figure out why that would happen.
If I do something like SELECTing only the values in the included columns of the index, it does what I would expect, an index seek, and just pulls everything from the index.
But if I SELECT *, why does it just bail on the index and do a scan when it seems like it would still benefit greatly from using it because it’s referenced in the WHERE clause?
Since you’re doing a
SELECT *and thus you retrieve all columns, SQL Server’s query optimizer may have decided it’s easier and more efficient to just do a clustered index scan – since it needs to go to the clustered index leaf level to get all the columns anyway (and doing a seek first, and then a key lookup to actually get the whole data page, is quite an expensive operation – scan might just be more efficient in this setup).I’m almost sure if you try
then there will be an index seek instead (since you’re only retrieving a single column – not everything).
That’s one of the reasons why I would recommend to be extra careful when using
SELECT * ....– try to avoid it if ever possible.