54

I ran this using MySql and it appears to not like TEXT. With SQL server I use nvarchar(max) What should I use in MySql? In other tables some fields will be descriptions and may be long so at the moment I am thinking that fixed length is bad.

create table if not exists 
    misc_info (
        id INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL,
        key TEXT UNIQUE NOT NULL,
        value TEXT NOT NULL
    )ENGINE=INNODB;

3 Answers 3

65

You can't have a UNIQUE index on a text column in MySQL.

If you want to index on a TEXT or a BLOB field, you must specify a fixed length to do that.

From MySQL documentation:

BLOB and TEXT columns also can be indexed, but a prefix length must be given.

Example:

CREATE UNIQUE INDEX index_name ON misc_info (key(10));
Sign up to request clarification or add additional context in comments.

5 Comments

And how do you make good use of the key in your queries? Using substring on the field?
You need a FULL TEXT INDEX to improve "substring" kind of queries. A regular index is useless.
How do you determine what length to set? Is the length in characters or bytes?
@KDawg, from the documentation: Prefix lengths are given in characters for nonbinary string types and in bytes for binary string types. That is, index entries consist of the first length characters of each column value for CHAR, VARCHAR, and TEXT columns, and the first length bytes of each column value for BINARY, VARBINARY, and BLOB columns.
If the index is limited, how does MySQL deal with hash collisions?
3

I think it chokes on the key field name rather than the TEXT type (which should be perfectly fine).

Reserved Words in mySQL

(And as @Pablo already said, memo fields can't be unique.)

1 Comment

I've not yet seen MySQL (from version 5 to 5.6) ever choke on using a ReservedWord. ReservedWords only require extra escaping in the select.
3

Two things:

  1. Key is a reserved word.
  2. You have to specify a length for a UNIQUE(key) TEXT value.

Comments

Your Answer

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