La lunghezza massima di una colonna VARCHAR in MySQL è limitata dalla dimensione massima di una riga, pari a 64KB (esclusi i BLOB). Il limite teorico è quindi:
VARCHAR(65535)
Tuttavia questo tetto si riduce con un set di caratteri multi-byte, poiché MySQL riserva fino a tre byte per carattere con utf8:
VARCHAR(21844) CHARACTER SET utf8
Ecco perché non è possibile raggiungere esattamente il massimo. Una colonna VARCHAR memorizza anche uno o due byte per registrare la lunghezza della stringa, quindi, anche quando è l'unica colonna, l'intera dimensione della riga non è utilizzabile:
mysql> CREATE TABLE foo ( v VARCHAR(65534) ); ERROR 1118 (42000): Row size too large. The maximum row size for the used table type, not counting BLOBs, is 65535. This includes storage overhead, check the manual. You have to change some columns to TEXT or BLOBs
Riducendo la lunghezza, il valore più grande che funziona davvero è:
mysql> CREATE TABLE foo ( v VARCHAR(65532) ); Query OK, 0 rows affected (0.01 sec)
Passando a un set di caratteri multi-byte a livello di tabella, ogni carattere viene conteggiato fino a tre byte, perché MySQL non può presumere che inserirai soltanto caratteri a un solo byte:
mysql> CREATE TABLE foo ( v VARCHAR(65532) ) CHARSET=utf8; ERROR 1074 (42000): Column length too big for column 'v' (max = 21845); use BLOB or TEXT instead
E, nonostante ciò che suggerisce l'errore, InnoDB si blocca comunque a 21845:
mysql> CREATE TABLE foo ( v VARCHAR(21845) ) CHARSET=utf8; ERROR 1118 (42000): Row size too large. The maximum row size for the used table type, not counting BLOBs, is 65535. This includes storage overhead, check the manual. You have to change some columns to TEXT or BLOBs
La matematica lo spiega: 21845 × 3 = 65535, che non ci sta, mentre 21844 × 3 = 65532, che invece ci sta:
mysql> CREATE TABLE foo ( v VARCHAR(21844) ) CHARSET=utf8; Query OK, 0 rows affected (0.32 sec)
Se hai davvero bisogno di memorizzare testi molto grandi, usa una colonna TEXT o BLOB invece di spingere VARCHAR ai suoi limiti.