9

I noticed in the SQL Server documentation that the list of referenced columns is not a required parameter of a foreign key constraint:

<column_constraint> ::= 
    [ CONSTRAINT constraint_name ] 
    {     { PRIMARY KEY | UNIQUE } 
            (...)

      | [ FOREIGN KEY ] 
            REFERENCES [ schema_name . ] referenced_table_name [ ( ref_column ) ] 
            [ ON DELETE { NO ACTION | CASCADE | SET NULL | SET DEFAULT } ] 
            [ ON UPDATE { NO ACTION | CASCADE | SET NULL | SET DEFAULT } ] 
            [ NOT FOR REPLICATION ] 

      | CHECK (...)
    }

If I omit the ( ref_column ) part, it seems to reference the primary key of the referenced_table_name. That is most convenient. However, I cannot find any specification of this behavior so I am cautious to use it.

Does anybody know whether it is specified anywhere?

Paul White
  • 94,921
  • 30
  • 437
  • 687
discrete
  • 199
  • 1
  • 2

2 Answers2

9

The behaviour is not explicitly mentioned in any of the official SQL Server documentation I am familiar with, but the 1992 Draft SQL Standard (section 11.8.2.b) does say:

If the <referenced table and columns> does not specify a <reference column list>, then the table descriptor of the referenced table shall include a unique constraint that specifies PRIMARY KEY. Let referenced columns be the column or columns identified by the unique columns in that unique constraint and let referenced column be one such column. The <referenced table and columns> shall be considered to implicitly specify a <reference column list> that is identical to that <unique column list>.

Translated, this means an implicit foreign key does reference the primary key of the referenced table. As others have mentioned in comments to the question, it is probably best to be explicit about the relationship though.

Paul White
  • 94,921
  • 30
  • 437
  • 687
0

If the Pk has multiple columns, and you don't specify the columns in the Fk specification, then it may get them wrong. I chased a bug for a while that turned out to be that the columns were wrong. For example:

FOREIGN KEY (OneID, TwoID) REFERENCES MySchema.ForeignTable

was interpreted as:

FOREIGN KEY (OneID, TwoID) REFERENCES MySchema.ForeignTable(TwoID, OneID)

If there is only Pk, then leaving the Pk Columns off is no problem, and is not ambiguous.

Gunnar
  • 111
  • 1