Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create foreign key on table with large size

When I use the following SQL Server command to add foreign key

ALTER TABLE [TABLE_A]
WITH CHECK ADD CONSTRAINT [FK_TABLE_A_TABLE_B]
FOREIGN KEY ([COLUMN_A]) REFERENCES [TABLE_B] ([COLUMN_A])

it will run very slow on tables with large size. Is there any faster/optimized way to add foreign key on table with large size?

Thanks!

like image 282
Robby Avatar asked Oct 19 '25 01:10

Robby


1 Answers

There is no online way to add a foreign key but you can do two things to make it faster:

  1. Create the two minimal indexes on the columns involved online. That reduces the amount of data to be read and it enables a merge join plan. You can use the "Showplan XML" profiler event to obtain the plan and validate it.
  2. Pull the indexes into memory: select count(*) from TABLE_A with (index(IX_TABLE_A_COLUMN_A)).

That reduces the time it takes to build a (trusted) foreign key.

like image 130
usr Avatar answered Oct 22 '25 05:10

usr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!