So I'm trying to create my table as follows:
CREATE TABLE company
(
id INT UNSIGNED PRIMARY KEY NOT NULL AUTO_INCREMENT,
name TEXT UNIQUE NOT NULL,
INDEX(name(20))
);
It's giving me this error:
ERROR 1170 (42000): BLOB/TEXT column 'name' used in key specification without a key length
I'm not sure why it's not working as I'm following the guide here: https://dev.mysql.com/doc/refman/5.5/en/column-indexes.html
FORCE INDEX works by only considering the given indexes (like with USE_INDEX) but in addition it tells the optimizer to regard a table scan as something very expensive. However if none of the 'forced' indexes can be used, then a table scan will be used anyway.
To create indexes, use the CREATE INDEX command: CREATE INDEX index_name ON table_name (column_name); You can an index on multiple columns.
In MariaDB, CREATE TABLE statement is used to create table within a selected database. Syntax: CREATE TABLE table_name (column_name column_type);
The show indexes statement allows you to query indexes from a table. In this syntax, you specify the name of the table from which you want to show the indexes. The show indexes returns the following information on indexes: table : is the name of the table to which the index belongs.
You're focusing on the wrong line.
name TEXT UNIQUE NOT NULL,
Indexes on BLOB
and TEXT
columns must be prefix indexes, therefore, it's not possible to impose a UNIQUE
constraint on a TEXT
column. You also can't make such a column part of the primary key or of a foreign key constraint.
Two common solutions:
Don't use an TEXT
column, use VARCHAR
.
If you really need a long column to be unique, create a second column of type CHAR
, COLLATE ascii_bin
, add a unique constraint to it, and size it appropriately for the base64 representation of a chosen cryptographic hash (md5, sha). Use BEFORE INSERT
and BEFORE UPDATE
triggers to force this column to contain the hash of the long column, thus indirectly enforcing uniqueness. Data type CHAR
because all hashes are the same length, and ascii_bin
because this is the most appropriate collation for base64. Why base64? It's a tradeoff of storage space for readability, using 24 characters to store an md5 hash, which is about halfway between binary (16 characters for md5, efficient) and hex (32 characters for md5, inefficient) encoding in terms of storage space.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With