Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Computed column index

I have a table Com_Main which contains column CompanyName nvarchar(250). It has average length of 19, max length = 250.

To improve performance I want to add a computed column left20_CompanyName which holds the first 20 characters of CompanyName:

alter table Com_main 
add left20_CompanyName as LEFT(CompanyName, 20) PERSISTED

Then I create Index on this column:

create index ix_com_main_left20CompanyName 
on Com_main (LEFT20_CompanyName)

So when I use

select CompanyName from Com_Main
where LEFT20_CompanyName LIKE '122%'

it uses this nonclustered index, but when the query is like:

select CompanyName from Com_Main 
where CompanyName LIKE '122%'

It uses full table scan, and don't use this index.

So the question:

Is it possible to make SQL Server use this index on computable column in last query?

like image 757
Mikhail Padlesny Avatar asked Oct 24 '12 14:10

Mikhail Padlesny


People also ask

What is a computed column index?

This means that the Database Engine stores the computed values in the table, and updates them when any other columns on which the computed column depends are updated. The Database Engine uses these persisted values when it creates an index on the column, and when the index is referenced in a query.

Can a computed column be a primary key?

A Computed Column cannot be used in a DEFAULT, FOREIGN KEY or NOT NULL constraints. If the expression that is used to define the Computed Column value is deterministic, the Computed Column can be involved in a PRIMARY KEY or UNIQUE constraint.


1 Answers

No. MySQL supports partial indexing of varchar columns but MS SQL Server does not.

You might be able to speed up table scans through partitioning but I don't know how smart SQL Server is in this regard.

like image 182
dwurf Avatar answered Oct 08 '22 18:10

dwurf