we have a big table with a varchar(max) column containing elements that are 'inspected' with charindex. For instance:
select x from y where charindex('string',[varchar_max_field]) > 0
In order to speed that up, I created a computed column with the result of the charindex command. As a test, I created both a persisted and a non-persisted version of that colum and created a nc-index for each, containing only the computed column:
CREATE TABLE [schema].[table] (
[other fields...]
[State] [NVARCHAR](MAX) NULL, /* Contains JSON information */
[NonPersistedColumn] AS (CHARINDEX('something',[State],(1))),
[PersistedColumn] AS (CHARINDEX('something',[State],(1))) PERSISTED )
CREATE NONCLUSTERED INDEX [ix_NonPersistedColumn] ON [schema].[table]
([NonPersistedColumn] ASC )
CREATE NONCLUSTERED INDEX [ix_PersistedColumn] ON [schema].[table]
([PersistedColumn] ASC )
Next,
SELECT TOP (50) [NonPersistedColumn] FROM [table] WHERE [NonPersistedColumn] > 0
uses an index seek on the index for the non-persisted column, as expected. However,
SELECT TOP (50) [PersistedColumn] FROM [table] WHERE [PersistedColumn] > 0
uses the index of the non-persisted column (equal charindex logic, so ok) and performs an identical index seek.
If I force it to use the index on the persisted column, it reverts to a Key Lookup on the clusterd index with table's ID column as a seek predicate and the [State] column in the query plan Output List. I am only asking for the column in the nc index, it is not a covering query.
Why is it using the PK index (containing an ID column)? Is that related to the PK always being added to the nc index? In this way, there is little advantage in persisting the computed column, or am I missing something?
Links to the the plans (persisted and non-persisted, respectively): https://www.brentozar.com/pastetheplan/?id=S1zoLmEEs https://www.brentozar.com/pastetheplan/?id=S1CHwmE4j
Link to the plan for the query on the persisted column without the index hint (uses the index on the non-persisted column) https://www.brentozar.com/pastetheplan/?id=HJB6j7EVs