Search code examples
mysqlprimary-keysurrogate-keynatural-key

Retrofit surrogate key in table with natural key in MySql?


Assume a table that uses a natural key and has a number of existing rows. What would be the easiest way to retrofit a surrogate key column and populate it with unique values using MySql?

I.e. transform

table employees
(
    social_security_no varchar(20),
    ...
    constraint emp_pk primary key (social_security_no)
);

to

table employees
(
    id int,
    social_security_no varchar(20),
    ...
    constraint emp_pk primary key (id)
);

and fill the new id column with valid id:s.

Thanks /Erik


Solution

  • Simple:

    ALTER TABLE employees DROP PRIMARY KEY;
    ALTER TABLE employees ADD (id INT AUTO_INCREMENT PRIMARY KEY);
    

    Optionally you'll (probably) want to do this:

    CREATE INDEX employees_ssn ON employees (social_security_no);
    

    and for any referencing tables:

    ALTER TABLE blah ADD (employees_fk INT);
    UPDATE blah b SET employees_fk = (SELECT id FROM employees WHERE social_security_no = b.ssn);
    ALTER TABLE blah DROP (ssn);