Search code examples
mysqlqtqsqlquery

mysql error 1062 during alter table modify column


I have a table that looks like this:

CREATE TABLE t1 (
    id BIGINT AUTO_INCREMENT NOT NULL PRIMARY KEY, 
    col1 VARCHAR(256),
    UNIQUE INDEX t1_col1_index (col1)
)

I'm trying to modify the col1 type using the following query:

ALTER TABLE t1 MODIFY COLUMN col1 varchar(191) COLLATE utf8mb4_unicode_ci;

However, I run into this duplication error:

error: ("1062", "QMYSQL3: Unable to execute statement", "Duplicate entry '+123456789' for key 't1_col1_index'")

I initially thought it could be because two or more rows might 'contain' similar value for col1 and on changing varchar length the data gets truncated but then I found out that data truncation wouldn't even allow the query to go through. Any pointers on what could be causing this?

EDIT (Resolved): Truncation does happen when @@sql_mode is not set with STRICT_TRANS_TABLES. This was causing the error.


Solution

  • You are reducing the length of a varchar column that is controlled by a UNIQUE constraint.

    This is risky business. Oversize data will be silently trimed (unless you have the @@sql_mode set to STRICT_TRANS_TABLES in which case an error will be raised). This probably generates duplicates, which cause the error to be raised by your UNIQUE constraint.

    You can check the max length of the values in your column with :

    SELECT MAX(CHAR_LENGTH(col1)) FROM t1: