3

MySQL Table

Now I want to add a primary key id column but it throws the error:

#1062 - Duplicate entry '0' for key 'PRIMARY'

I already tried this: Add primary key to existing table

3
  • As you can see you have more than one entry with id 0 in your table. A Primary key must be unique. So you have to make the id's unique before you can add the Primary key Commented May 10, 2017 at 12:43
  • @Jens do I need to manually change it? Commented May 10, 2017 at 12:44
  • Yes i think so.. Commented May 10, 2017 at 12:52

2 Answers 2

3

When you creates a new column, a default value is asigned (in your case will be 0), so you need to specify wich values will it have (besides you can tell it to the column to be autoincremental, and it will do the work for you for the new entries of rows). You have to change all the values to be differents between them, the id key MUST be unique

To change all your ids, in mysql you can do:

SET @new_id=0; UPDATE your_table SET id = @new_id := @new_id + 1 where id = 0 
Sign up to request clarification or add additional context in comments.

3 Comments

I know this bro but I forgot to add primary key
I add you a way to update your table in mysql :), now you know how to do it
No problem pal, I have always loved to help, your question will help a lot!
0

First please change ids of the table with below query

SET @counter = 1 UPDATE #tablename SET @counter = id = @counter + 1 

And then Apply primary key.

2 Comments

It shows the following error #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DECLARE counter int SET counter = 0 UPDATE images_proposals SET counter = ' at line 1
I removed @ it didn't allow me to post

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.