Tech
Adding a foreign key to a big table without locking both of them
Foreign keys are the constraint people add late. The table already has a few million rows in it, someone notices that order_items.order_id can point at nothing, and the fix is one line.
ALTER TABLE order_items
ADD CONSTRAINT order_items_order_id_fkey
FOREIGN KEY ( order_id ) REFERENCES orders ( id );
This statement does two things. It records the constraint, which is instant, and it validates it, which means scanning every row of order_items ...
Read the full discussion on Dev.to
This article was aggregated from Dev.to. Click to join the conversation.
View on Dev.to