mysql: ERROR 1062 (23000): Duplicate entry '...' for key 'PRIMARY

This is a wiki page. Be bold and improve it!

If you have any questions about the content on this page, don't hesitate to open a new ticket and we'll do our best to assist you.

Query:

mysql> ALTER TABLE `my_table` ADD PRIMARY KEY ( `id` );

A primary key cannot contain duplicate entries. You can see duplicates thus:

mysql > SELECT id, COUNT(id) AS count FROM my_table GROUP BY id HAVING count > 1 ORDER BY count;

The proper way to remove duplicate rows will depend on the table layout, what data must be kept and what can be discarded.