5

I have a table with 3 columns: a list id, name and numeric value. The goal is to use the table to retrieve and update the numeric value for a name in various lists.

The problem is that sql refuses to create an index with the name column because it's a string column with variable length.

Without an index selecting with a name will be inefficient, and the option of using a static length text column will be wasting a lot of storage space as names can be fairly long.

What is the best way to build this table and it's indexes?

(running sql server 2008)

2
  • How long is the string column? What is the actual error? What is the purpose of the index, to satisfy seeks better? Commented Feb 26, 2012 at 18:00
  • 1
    Any index in SQL Server can be a maximum of 900 bytes per index entry - if your string column is longer than that, you cannot index it. Show us your exact, complete table structure! Commented Feb 26, 2012 at 18:00

2 Answers 2

9

If your string is longer than 900 bytes, then it can't be an index key, regardless of whether it is variable or fixed length.

One idea would be to at least make seeks more selective by adding a computed column. e.g.

CREATE TABLE dbo.Strings
(
  -- other columns,
  WholeString VARCHAR(4000),
  Substring AS (CONVERT(VARCHAR(10), WholeString) PERSISTED
);
CREATE INDEX ss ON dbo.Strings(Substring);

Now when searching for a row to update, you can say:

WHERE s.Substring = LEFT(@string, 10)
AND s.WholeString = @string;

This will at least help the optimizer narrow its search down to the index pages where the exact match is most likely to live. You may want to experiment with that length as it depends on how many similar strings you have and what will best help the optimizer weed out a single page. You may also want to experiment with including some or all of the other columns in the ss index, with or without using the INCLUDE clause (whether this is useful will vary greatly on various factors such as what else your update query does, read/write ratio, etc).

Sign up to request clarification or add additional context in comments.

Comments

5

A regular index can't be created on ntext or text columns (i guess your name column is of that type, or (n)varchar longer than 900 bytes). You can create full-text index on that column type.

1 Comment

I'm not sure why you think "name" must be using a deprecated data type. Also have you tried creating an index on a varchar(max) column? A hint: this is not a valid index. You can add a varchar(max) column as an INCLUDE column, but this is rarely wise and won't help the search anyway.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.