Skip to content
Advertisement

mysql Duplicate entry error for primary key with similar values

This is how i created my table, i have composite key columns.

CREATE TABLE platformExchangePair(
pairName VARCHAR(15),
idExchangePlatform INT,
PRIMARY KEY (pairName,idExchangePlatform),
FOREIGN KEY (idExchangePlatform) REFERENCES exchangePlatform(idExchangePlatform)
);

now, im trying to insert this two values that are the same except for the last character ‘t’:

value1 = testbtc:testusd

value2 = testbtc:testusdt

INSERT INTO platformExchangePair (pairName,idExchangePlatform) 
VALUES ('testbtc:testusd',1),('testbtc:testusdt',1);

output error:

1 Duplicate entry 'testbtc:testusd-1' for key 'platformExchangePair.PRIMARY' SQL.sql 75 1 

it just makes no sense, they are not duplicated, is something missing on my table?

Advertisement

Answer

I suspect that the version of MySql you are using is 5.5.x, in which case when you try to insert a value for a VARCHAR column that is longer than its defined length, in your case longer than 15, the value is truncated to the max length.

So, because the length of 'testbtc:testusdt' is 16, it is truncated to 'testbtc:testusd' (the first 15 chars) and the result is the dupicate.

See a simplified demo.

The best you can do is increase the size of the column:

ALTER TABLE platformExchangePair MODIFY COLUMN pairName VARCHAR(20);
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement