Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reduce clustered index scan cost by using SQL query

How can I reduce the clustered index scan cost of below mentioned query

DECLARE @PARAMVAL varchar(3)  set @PARAMVAL = 'CTD' select * from MASTER_RECORD_TYPE where RECORD_TYPE_CODE=@PARAMVAL 

if I run the above query it was showing index scan 99 %

Please find here below my table particularities:

enter image description here

here below i have pasted my index for the table:

CREATE TABLE [dbo].[MASTER_RECORD_TYPE] ADD  CONSTRAINT [PK_MASTER_REPORD_TYPE] PRIMARY KEY CLUSTERED  (     [Record_Type_Id] ASC )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 80) ON [PRIMARY] GO 

kindly advise how can i reduce index scan cost?

like image 754
user1494292 Avatar asked Aug 06 '12 10:08

user1494292


People also ask

How can use clustered index in SQL query?

On the Table Designer menu, click Indexes/Keys. In the Indexes/Keys dialog box, click Add. Select the new index in the Selected Primary/Unique Key or Index text box. In the grid, select Create as Clustered, and choose Yes from the drop-down list to the right of the property.

What is Clustered index scan in SQL?

We can say, a Clustered Index Scan is same like a Table Scan operation i.e. entire index is traversed row by row to return the data set. If the SQL Server optimizer determines there are so many rows need to be returned it is quicker to scan all rows than to use index keys.


2 Answers

First of all - if you search for RECORD_TYPE_CODE you should make sure to have an index on that column.

Besides that mainly two things:

  • don't use SELECT * - that'll always have to go back to the clustered index to get the full data page; use a SELECT that explicitly specifies which columns to use

  • if ever possible, try to find a way to have a covering nonclustered index, e.g. an index that contains all the columns needed to satisfy the query

If you have such a covering nonclustered index, then the query optimizer will most likely use that covering index (instead of the actual clustered index which is the full table data) to fetch the results

like image 71
marc_s Avatar answered Oct 21 '22 12:10

marc_s


You need to try and use a covered index. But the problem you're going to have is that you're using SELECT *. Do you really need the entire record?

Either way, add RECORD_TYPE_CODE to another index and it will help with the query because at least that field can be read off of an index page.

like image 24
Mike Perrenoud Avatar answered Oct 21 '22 11:10

Mike Perrenoud