Question

I think the following is a standard coding "pattern" when we need to change the primary key of a table to serve better our queries via the index:

ALTER TABLE employees   
  ADD UNIQUE INDEX tmp (employee_id, subsidiary_id);  

ALTER TABLE employees  
 DROP PRIMARY KEY;  

ALTER TABLE employees  
  ADD PRIMARY KEY (subsidiary_id, employee_id);  

My understanding is that the tmp index is created before dropping the primary key in order to facilitate queries using the current primary key and not lose performance.
But I don't understand this.
When we execute an ALTER TABLE (I am referring to the ALTER TABLE to drop the primary key) the table will be locked until the operation finishes right?
So the queries will not be able to run anyway. So why create tmp in the first place?

Was it helpful?

Solution

I haven't seen this pattern. But, I would expect it for a slightly different reason. The purpose is less "facilitating" queries than ensuring that the pair of keys remains unique throughout the entire set of transactions.

In other words, between dropping the primary key and creating the new key, there is a short window of opportunity for someone to insert a duplicate pair of keys. Then the second operation will fail. By creating the unique index first, you prevent this from happening.

If you know there are no other users/queries using the system when you are modifying the table (say you are in single user mode), then there is no need to create the additional index.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top