mysqlvarchar

Equivalent of varchar(max) in MySQL?


What is the equivalent of varchar(max) in MySQL?


Solution

  • The max length of a varchar is subject to the max row size in MySQL, which is 64KB (not counting BLOBs):

    VARCHAR(65535)
    

    However, note that the limit is lower if you use a multi-byte character set:

    VARCHAR(21844) CHARACTER SET utf8
    

    Here are some examples:

    The maximum row size is 65535, but a varchar also includes a byte or two to encode the length of a given string. So you actually can't declare a varchar of the maximum row size, even if it's the only column in the table.

    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
    

    But if we try decreasing lengths, we find the greatest length that works:

    mysql> CREATE TABLE foo ( v VARCHAR(65532) );
    Query OK, 0 rows affected (0.01 sec)
    

    Now if we try to use a multibyte charset at the table level, we find that it counts each character as multiple bytes. UTF8 strings don't necessarily use multiple bytes per string, but MySQL can't assume you'll restrict all your future inserts to single-byte characters.

    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
    

    In spite of what the last error told us, InnoDB still doesn't like a length of 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
    

    This makes perfect sense, if you calculate that 21845*3 = 65535, which wouldn't have worked anyway. Whereas 21844*3 = 65532, which does work.

    mysql> CREATE TABLE foo ( v VARCHAR(21844) ) CHARSET=utf8;
    Query OK, 0 rows affected (0.32 sec)