The use of multiple foreign keys on same column in SQL Serverforeign key constraints on same tableChanging field length when foreign keys reference primary key field in tableNeed for indexes on foreign keysComposite primary key from multiple tables / multiple foreign keysForeign Keys to tables where primary key is not clustered indexWhat would I use a MATCH SIMPLE foreign key for?Multiple foreign keys on single columnSQL Server database design with foreign keysComposite Primary Key on partitioned tables, and Foreign KeysIs it best practice to use surrogate keys when creating foreign key constraints in SQL Server?

Is it wise to hold on to stock that has plummeted and then stabilized?

Could a US political party gain complete control over the government by removing checks & balances?

Need help identifying/translating a plaque in Tangier, Morocco

COUNT(*) or MAX(id) - which is faster?

How did the USSR manage to innovate in an environment characterized by government censorship and high bureaucracy?

What does "enim et" mean?

Typesetting a double Over Dot on top of a symbol

How to deal with fear of taking dependencies

Prime joint compound before latex paint?

Extreme, but not acceptable situation and I can't start the work tomorrow morning

aging parents with no investments

Does bootstrapped regression allow for inference?

How can I fix this gap between bookcases I made?

Ideas for 3rd eye abilities

"My colleague's body is amazing"

Domain expired, GoDaddy holds it and is asking more money

Why is my log file so massive? 22gb. I am running log backups

Re-submission of rejected manuscript without informing co-authors

Is domain driven design an anti-SQL pattern?

Is there a way to make member function NOT callable from constructor?

What is GPS' 19 year rollover and does it present a cybersecurity issue?

LWC and complex parameters

Crop image to path created in TikZ?

Is ipsum/ipsa/ipse a third person pronoun, or can it serve other functions?



The use of multiple foreign keys on same column in SQL Server


foreign key constraints on same tableChanging field length when foreign keys reference primary key field in tableNeed for indexes on foreign keysComposite primary key from multiple tables / multiple foreign keysForeign Keys to tables where primary key is not clustered indexWhat would I use a MATCH SIMPLE foreign key for?Multiple foreign keys on single columnSQL Server database design with foreign keysComposite Primary Key on partitioned tables, and Foreign KeysIs it best practice to use surrogate keys when creating foreign key constraints in SQL Server?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








9















SQL Server allows me to create multiple foreign keys on a column, and each time using just different name I can create another key referencing to the same object. Basically all the keys are defining the same relationship. I want to know what's the use of having multiple foreign keys which are defined on the same column and reference to the same column in another table. What's the benefit of it that SQL Server allows us to do a thing like that?



enter image description here










share|improve this question




























    9















    SQL Server allows me to create multiple foreign keys on a column, and each time using just different name I can create another key referencing to the same object. Basically all the keys are defining the same relationship. I want to know what's the use of having multiple foreign keys which are defined on the same column and reference to the same column in another table. What's the benefit of it that SQL Server allows us to do a thing like that?



    enter image description here










    share|improve this question
























      9












      9








      9


      2






      SQL Server allows me to create multiple foreign keys on a column, and each time using just different name I can create another key referencing to the same object. Basically all the keys are defining the same relationship. I want to know what's the use of having multiple foreign keys which are defined on the same column and reference to the same column in another table. What's the benefit of it that SQL Server allows us to do a thing like that?



      enter image description here










      share|improve this question














      SQL Server allows me to create multiple foreign keys on a column, and each time using just different name I can create another key referencing to the same object. Basically all the keys are defining the same relationship. I want to know what's the use of having multiple foreign keys which are defined on the same column and reference to the same column in another table. What's the benefit of it that SQL Server allows us to do a thing like that?



      enter image description here







      sql-server foreign-key






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked 2 days ago









      ElGrigElGrig

      734117




      734117




















          5 Answers
          5






          active

          oldest

          votes


















          14














          SQL Server allows you to do a lot of silly things.



          You can even create a foreign key on a column referencing itself - despite the fact that this can never be violated as every row will meet the constraint on itself.



          One edge case where the ability to create two foreign keys on the same relationship would be potentially useful is because the index used for validating foreign keys is determined at creation time. If a better (i.e. narrower) index comes along later then this would allow a new foreign key constraint to be created bound on the better index and then the original constraint dropped without having any gap with no active constraint.



          (As in example below)



          CREATE TABLE T1(
          T1_Id INT PRIMARY KEY CLUSTERED NOT NULL,
          Filler CHAR(4000) NULL,
          )

          INSERT INTO T1 VALUES (1, '');

          CREATE TABLE T2(
          T2_Id INT IDENTITY(1,1) PRIMARY KEY NOT NULL,
          T1_Id INT NOT NULL CONSTRAINT FK REFERENCES T1 (T1_Id),
          Filler CHAR(4000) NULL,
          )


          ALTER TABLE T1 ADD CONSTRAINT
          UQ_T1 UNIQUE NONCLUSTERED(T1_Id)


          /*Execution Plan uses clustered index*/
          INSERT INTO T2 VALUES (1,1)

          ALTER TABLE T2 WITH CHECK ADD CONSTRAINT FK2 FOREIGN KEY(T1_Id)
          REFERENCES T1 (T1_Id)

          ALTER TABLE T2 DROP CONSTRAINT FK

          /*Now Execution Plan now uses non clustered index*/
          INSERT INTO T2 VALUES (1,1)

          DROP TABLE T2, T1;


          As an aside for the interim period whilst both constraints exist any inserts end up being validated against both indexes.






          share|improve this answer
































            11














            There is no use for having identical foreign key constraints., that is on same columns and referencing same table and columns.



            It's like having the same check 2 or more times.






            share|improve this answer
































              9














              There is no benefit to having redundant constraints that differ only by name. Similarly, there is no benefit to having redundant indexes that differ only by name. Both add overhead without value.



              The SQL Server database engine does not stop you from doing so. Good constraint naming constraint naming conventions (e.g. FK_ReferencingTable_ReferencedTable) can help protect one against such mistakes.






              share|improve this answer
































                4














                Same reason you can create 50 indexes on the same column, add a second log file, set max server memory to 20MB... most people won't do these things, but there can be legitimate reasons to do them occasionally, so there's no benefit in creating overhead in the engine to add checks against things that are merely ill-advised.






                share|improve this answer






























                  1














                  Sounds like a blue-green thing.



                  When you begin to cutover from blue to green, you need to temporarily create extra copies of things.



                  What we want to do is temporarily create an extra foreign key CHECK WITH NOCHECK and ON UPDATE CASCADE ON DELETE SET NULL; what this does is it is a working foreign key but the existing rows aren't checked when the key is created.



                  Later after cleaning up all the rows that should match we would create the new foreign key without any command options (default is CHECK WITH CHECK which is what you typically want), and drop the temporary foreign key.



                  Notice that if you just dropped and recreated the foreign key, some garbage rows could slip by you.






                  share|improve this answer























                    Your Answer








                    StackExchange.ready(function()
                    var channelOptions =
                    tags: "".split(" "),
                    id: "182"
                    ;
                    initTagRenderer("".split(" "), "".split(" "), channelOptions);

                    StackExchange.using("externalEditor", function()
                    // Have to fire editor after snippets, if snippets enabled
                    if (StackExchange.settings.snippets.snippetsEnabled)
                    StackExchange.using("snippets", function()
                    createEditor();
                    );

                    else
                    createEditor();

                    );

                    function createEditor()
                    StackExchange.prepareEditor(
                    heartbeatType: 'answer',
                    autoActivateHeartbeat: false,
                    convertImagesToLinks: false,
                    noModals: true,
                    showLowRepImageUploadWarning: true,
                    reputationToPostImages: null,
                    bindNavPrevention: true,
                    postfix: "",
                    imageUploader:
                    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                    allowUrls: true
                    ,
                    onDemand: true,
                    discardSelector: ".discard-answer"
                    ,immediatelyShowMarkdownHelp:true
                    );



                    );













                    draft saved

                    draft discarded


















                    StackExchange.ready(
                    function ()
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fdba.stackexchange.com%2fquestions%2f234086%2fthe-use-of-multiple-foreign-keys-on-same-column-in-sql-server%23new-answer', 'question_page');

                    );

                    Post as a guest















                    Required, but never shown

























                    5 Answers
                    5






                    active

                    oldest

                    votes








                    5 Answers
                    5






                    active

                    oldest

                    votes









                    active

                    oldest

                    votes






                    active

                    oldest

                    votes









                    14














                    SQL Server allows you to do a lot of silly things.



                    You can even create a foreign key on a column referencing itself - despite the fact that this can never be violated as every row will meet the constraint on itself.



                    One edge case where the ability to create two foreign keys on the same relationship would be potentially useful is because the index used for validating foreign keys is determined at creation time. If a better (i.e. narrower) index comes along later then this would allow a new foreign key constraint to be created bound on the better index and then the original constraint dropped without having any gap with no active constraint.



                    (As in example below)



                    CREATE TABLE T1(
                    T1_Id INT PRIMARY KEY CLUSTERED NOT NULL,
                    Filler CHAR(4000) NULL,
                    )

                    INSERT INTO T1 VALUES (1, '');

                    CREATE TABLE T2(
                    T2_Id INT IDENTITY(1,1) PRIMARY KEY NOT NULL,
                    T1_Id INT NOT NULL CONSTRAINT FK REFERENCES T1 (T1_Id),
                    Filler CHAR(4000) NULL,
                    )


                    ALTER TABLE T1 ADD CONSTRAINT
                    UQ_T1 UNIQUE NONCLUSTERED(T1_Id)


                    /*Execution Plan uses clustered index*/
                    INSERT INTO T2 VALUES (1,1)

                    ALTER TABLE T2 WITH CHECK ADD CONSTRAINT FK2 FOREIGN KEY(T1_Id)
                    REFERENCES T1 (T1_Id)

                    ALTER TABLE T2 DROP CONSTRAINT FK

                    /*Now Execution Plan now uses non clustered index*/
                    INSERT INTO T2 VALUES (1,1)

                    DROP TABLE T2, T1;


                    As an aside for the interim period whilst both constraints exist any inserts end up being validated against both indexes.






                    share|improve this answer





























                      14














                      SQL Server allows you to do a lot of silly things.



                      You can even create a foreign key on a column referencing itself - despite the fact that this can never be violated as every row will meet the constraint on itself.



                      One edge case where the ability to create two foreign keys on the same relationship would be potentially useful is because the index used for validating foreign keys is determined at creation time. If a better (i.e. narrower) index comes along later then this would allow a new foreign key constraint to be created bound on the better index and then the original constraint dropped without having any gap with no active constraint.



                      (As in example below)



                      CREATE TABLE T1(
                      T1_Id INT PRIMARY KEY CLUSTERED NOT NULL,
                      Filler CHAR(4000) NULL,
                      )

                      INSERT INTO T1 VALUES (1, '');

                      CREATE TABLE T2(
                      T2_Id INT IDENTITY(1,1) PRIMARY KEY NOT NULL,
                      T1_Id INT NOT NULL CONSTRAINT FK REFERENCES T1 (T1_Id),
                      Filler CHAR(4000) NULL,
                      )


                      ALTER TABLE T1 ADD CONSTRAINT
                      UQ_T1 UNIQUE NONCLUSTERED(T1_Id)


                      /*Execution Plan uses clustered index*/
                      INSERT INTO T2 VALUES (1,1)

                      ALTER TABLE T2 WITH CHECK ADD CONSTRAINT FK2 FOREIGN KEY(T1_Id)
                      REFERENCES T1 (T1_Id)

                      ALTER TABLE T2 DROP CONSTRAINT FK

                      /*Now Execution Plan now uses non clustered index*/
                      INSERT INTO T2 VALUES (1,1)

                      DROP TABLE T2, T1;


                      As an aside for the interim period whilst both constraints exist any inserts end up being validated against both indexes.






                      share|improve this answer



























                        14












                        14








                        14







                        SQL Server allows you to do a lot of silly things.



                        You can even create a foreign key on a column referencing itself - despite the fact that this can never be violated as every row will meet the constraint on itself.



                        One edge case where the ability to create two foreign keys on the same relationship would be potentially useful is because the index used for validating foreign keys is determined at creation time. If a better (i.e. narrower) index comes along later then this would allow a new foreign key constraint to be created bound on the better index and then the original constraint dropped without having any gap with no active constraint.



                        (As in example below)



                        CREATE TABLE T1(
                        T1_Id INT PRIMARY KEY CLUSTERED NOT NULL,
                        Filler CHAR(4000) NULL,
                        )

                        INSERT INTO T1 VALUES (1, '');

                        CREATE TABLE T2(
                        T2_Id INT IDENTITY(1,1) PRIMARY KEY NOT NULL,
                        T1_Id INT NOT NULL CONSTRAINT FK REFERENCES T1 (T1_Id),
                        Filler CHAR(4000) NULL,
                        )


                        ALTER TABLE T1 ADD CONSTRAINT
                        UQ_T1 UNIQUE NONCLUSTERED(T1_Id)


                        /*Execution Plan uses clustered index*/
                        INSERT INTO T2 VALUES (1,1)

                        ALTER TABLE T2 WITH CHECK ADD CONSTRAINT FK2 FOREIGN KEY(T1_Id)
                        REFERENCES T1 (T1_Id)

                        ALTER TABLE T2 DROP CONSTRAINT FK

                        /*Now Execution Plan now uses non clustered index*/
                        INSERT INTO T2 VALUES (1,1)

                        DROP TABLE T2, T1;


                        As an aside for the interim period whilst both constraints exist any inserts end up being validated against both indexes.






                        share|improve this answer















                        SQL Server allows you to do a lot of silly things.



                        You can even create a foreign key on a column referencing itself - despite the fact that this can never be violated as every row will meet the constraint on itself.



                        One edge case where the ability to create two foreign keys on the same relationship would be potentially useful is because the index used for validating foreign keys is determined at creation time. If a better (i.e. narrower) index comes along later then this would allow a new foreign key constraint to be created bound on the better index and then the original constraint dropped without having any gap with no active constraint.



                        (As in example below)



                        CREATE TABLE T1(
                        T1_Id INT PRIMARY KEY CLUSTERED NOT NULL,
                        Filler CHAR(4000) NULL,
                        )

                        INSERT INTO T1 VALUES (1, '');

                        CREATE TABLE T2(
                        T2_Id INT IDENTITY(1,1) PRIMARY KEY NOT NULL,
                        T1_Id INT NOT NULL CONSTRAINT FK REFERENCES T1 (T1_Id),
                        Filler CHAR(4000) NULL,
                        )


                        ALTER TABLE T1 ADD CONSTRAINT
                        UQ_T1 UNIQUE NONCLUSTERED(T1_Id)


                        /*Execution Plan uses clustered index*/
                        INSERT INTO T2 VALUES (1,1)

                        ALTER TABLE T2 WITH CHECK ADD CONSTRAINT FK2 FOREIGN KEY(T1_Id)
                        REFERENCES T1 (T1_Id)

                        ALTER TABLE T2 DROP CONSTRAINT FK

                        /*Now Execution Plan now uses non clustered index*/
                        INSERT INTO T2 VALUES (1,1)

                        DROP TABLE T2, T1;


                        As an aside for the interim period whilst both constraints exist any inserts end up being validated against both indexes.







                        share|improve this answer














                        share|improve this answer



                        share|improve this answer








                        edited 2 days ago

























                        answered 2 days ago









                        Martin SmithMartin Smith

                        64.2k10173259




                        64.2k10173259























                            11














                            There is no use for having identical foreign key constraints., that is on same columns and referencing same table and columns.



                            It's like having the same check 2 or more times.






                            share|improve this answer





























                              11














                              There is no use for having identical foreign key constraints., that is on same columns and referencing same table and columns.



                              It's like having the same check 2 or more times.






                              share|improve this answer



























                                11












                                11








                                11







                                There is no use for having identical foreign key constraints., that is on same columns and referencing same table and columns.



                                It's like having the same check 2 or more times.






                                share|improve this answer















                                There is no use for having identical foreign key constraints., that is on same columns and referencing same table and columns.



                                It's like having the same check 2 or more times.







                                share|improve this answer














                                share|improve this answer



                                share|improve this answer








                                edited 2 days ago

























                                answered 2 days ago









                                ypercubeᵀᴹypercubeᵀᴹ

                                78.3k11137221




                                78.3k11137221





















                                    9














                                    There is no benefit to having redundant constraints that differ only by name. Similarly, there is no benefit to having redundant indexes that differ only by name. Both add overhead without value.



                                    The SQL Server database engine does not stop you from doing so. Good constraint naming constraint naming conventions (e.g. FK_ReferencingTable_ReferencedTable) can help protect one against such mistakes.






                                    share|improve this answer





























                                      9














                                      There is no benefit to having redundant constraints that differ only by name. Similarly, there is no benefit to having redundant indexes that differ only by name. Both add overhead without value.



                                      The SQL Server database engine does not stop you from doing so. Good constraint naming constraint naming conventions (e.g. FK_ReferencingTable_ReferencedTable) can help protect one against such mistakes.






                                      share|improve this answer



























                                        9












                                        9








                                        9







                                        There is no benefit to having redundant constraints that differ only by name. Similarly, there is no benefit to having redundant indexes that differ only by name. Both add overhead without value.



                                        The SQL Server database engine does not stop you from doing so. Good constraint naming constraint naming conventions (e.g. FK_ReferencingTable_ReferencedTable) can help protect one against such mistakes.






                                        share|improve this answer















                                        There is no benefit to having redundant constraints that differ only by name. Similarly, there is no benefit to having redundant indexes that differ only by name. Both add overhead without value.



                                        The SQL Server database engine does not stop you from doing so. Good constraint naming constraint naming conventions (e.g. FK_ReferencingTable_ReferencedTable) can help protect one against such mistakes.







                                        share|improve this answer














                                        share|improve this answer



                                        share|improve this answer








                                        edited yesterday

























                                        answered 2 days ago









                                        Dan GuzmanDan Guzman

                                        14.1k21736




                                        14.1k21736





















                                            4














                                            Same reason you can create 50 indexes on the same column, add a second log file, set max server memory to 20MB... most people won't do these things, but there can be legitimate reasons to do them occasionally, so there's no benefit in creating overhead in the engine to add checks against things that are merely ill-advised.






                                            share|improve this answer



























                                              4














                                              Same reason you can create 50 indexes on the same column, add a second log file, set max server memory to 20MB... most people won't do these things, but there can be legitimate reasons to do them occasionally, so there's no benefit in creating overhead in the engine to add checks against things that are merely ill-advised.






                                              share|improve this answer

























                                                4












                                                4








                                                4







                                                Same reason you can create 50 indexes on the same column, add a second log file, set max server memory to 20MB... most people won't do these things, but there can be legitimate reasons to do them occasionally, so there's no benefit in creating overhead in the engine to add checks against things that are merely ill-advised.






                                                share|improve this answer













                                                Same reason you can create 50 indexes on the same column, add a second log file, set max server memory to 20MB... most people won't do these things, but there can be legitimate reasons to do them occasionally, so there's no benefit in creating overhead in the engine to add checks against things that are merely ill-advised.







                                                share|improve this answer












                                                share|improve this answer



                                                share|improve this answer










                                                answered 2 days ago









                                                Aaron BertrandAaron Bertrand

                                                154k18298493




                                                154k18298493





















                                                    1














                                                    Sounds like a blue-green thing.



                                                    When you begin to cutover from blue to green, you need to temporarily create extra copies of things.



                                                    What we want to do is temporarily create an extra foreign key CHECK WITH NOCHECK and ON UPDATE CASCADE ON DELETE SET NULL; what this does is it is a working foreign key but the existing rows aren't checked when the key is created.



                                                    Later after cleaning up all the rows that should match we would create the new foreign key without any command options (default is CHECK WITH CHECK which is what you typically want), and drop the temporary foreign key.



                                                    Notice that if you just dropped and recreated the foreign key, some garbage rows could slip by you.






                                                    share|improve this answer



























                                                      1














                                                      Sounds like a blue-green thing.



                                                      When you begin to cutover from blue to green, you need to temporarily create extra copies of things.



                                                      What we want to do is temporarily create an extra foreign key CHECK WITH NOCHECK and ON UPDATE CASCADE ON DELETE SET NULL; what this does is it is a working foreign key but the existing rows aren't checked when the key is created.



                                                      Later after cleaning up all the rows that should match we would create the new foreign key without any command options (default is CHECK WITH CHECK which is what you typically want), and drop the temporary foreign key.



                                                      Notice that if you just dropped and recreated the foreign key, some garbage rows could slip by you.






                                                      share|improve this answer

























                                                        1












                                                        1








                                                        1







                                                        Sounds like a blue-green thing.



                                                        When you begin to cutover from blue to green, you need to temporarily create extra copies of things.



                                                        What we want to do is temporarily create an extra foreign key CHECK WITH NOCHECK and ON UPDATE CASCADE ON DELETE SET NULL; what this does is it is a working foreign key but the existing rows aren't checked when the key is created.



                                                        Later after cleaning up all the rows that should match we would create the new foreign key without any command options (default is CHECK WITH CHECK which is what you typically want), and drop the temporary foreign key.



                                                        Notice that if you just dropped and recreated the foreign key, some garbage rows could slip by you.






                                                        share|improve this answer













                                                        Sounds like a blue-green thing.



                                                        When you begin to cutover from blue to green, you need to temporarily create extra copies of things.



                                                        What we want to do is temporarily create an extra foreign key CHECK WITH NOCHECK and ON UPDATE CASCADE ON DELETE SET NULL; what this does is it is a working foreign key but the existing rows aren't checked when the key is created.



                                                        Later after cleaning up all the rows that should match we would create the new foreign key without any command options (default is CHECK WITH CHECK which is what you typically want), and drop the temporary foreign key.



                                                        Notice that if you just dropped and recreated the foreign key, some garbage rows could slip by you.







                                                        share|improve this answer












                                                        share|improve this answer



                                                        share|improve this answer










                                                        answered 2 days ago









                                                        JoshuaJoshua

                                                        1436




                                                        1436



























                                                            draft saved

                                                            draft discarded
















































                                                            Thanks for contributing an answer to Database Administrators Stack Exchange!


                                                            • Please be sure to answer the question. Provide details and share your research!

                                                            But avoid


                                                            • Asking for help, clarification, or responding to other answers.

                                                            • Making statements based on opinion; back them up with references or personal experience.

                                                            To learn more, see our tips on writing great answers.




                                                            draft saved


                                                            draft discarded














                                                            StackExchange.ready(
                                                            function ()
                                                            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fdba.stackexchange.com%2fquestions%2f234086%2fthe-use-of-multiple-foreign-keys-on-same-column-in-sql-server%23new-answer', 'question_page');

                                                            );

                                                            Post as a guest















                                                            Required, but never shown





















































                                                            Required, but never shown














                                                            Required, but never shown












                                                            Required, but never shown







                                                            Required, but never shown

































                                                            Required, but never shown














                                                            Required, but never shown












                                                            Required, but never shown







                                                            Required, but never shown







                                                            Popular posts from this blog

                                                            Tamil (spriik) Luke uk diar | Nawigatjuun

                                                            Align equal signs while including text over equalitiesAMS align: left aligned text/math plus multicolumn alignmentMultiple alignmentsAligning equations in multiple placesNumbering and aligning an equation with multiple columnsHow to align one equation with another multline equationUsing \ in environments inside the begintabularxNumber equations and preserving alignment of equal signsHow can I align equations to the left and to the right?Double equation alignment problem within align enviromentAligned within align: Why are they right-aligned?

                                                            Training a classifier when some of the features are unknownWhy does Gradient Boosting regression predict negative values when there are no negative y-values in my training set?How to improve an existing (trained) classifier?What is effect when I set up some self defined predisctor variables?Why Matlab neural network classification returns decimal values on prediction dataset?Fitting and transforming text data in training, testing, and validation setsHow to quantify the performance of the classifier (multi-class SVM) using the test data?How do I control for some patients providing multiple samples in my training data?Training and Test setTraining a convolutional neural network for image denoising in MatlabShouldn't an autoencoder with #(neurons in hidden layer) = #(neurons in input layer) be “perfect”?