Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the meaning of self referencing foreign key?

I went over a legacy database and found a couple of foreign keys that reference a column to itself. The referenced column is the primary key column.

ALTER TABLE [SchemaName].[TableName]  WITH CHECK ADD  
CONSTRAINT [FK_TableName_TableName] FOREIGN KEY([Id])
REFERENCES [SchemaName].[TableName] ([Id])

What is the meaning of it?

like image 721
HuBeZa Avatar asked Nov 11 '12 11:11

HuBeZa


People also ask

Can foreign key reference itself?

what is Self Referencing Foreign Key? Sometimes Foreign Key of a table references back to the primary key of the same table. In that case, the Foreign Key is said to be self-referencing. In this table, the 'employee_id' column is the primary key and the 'manager_id' is the foreign key.

How do you reference a foreign key?

A FOREIGN KEY is a field (or collection of fields) in one table, that refers to the PRIMARY KEY in another table. The table with the foreign key is called the child table, and the table with the primary key is called the referenced or parent table.

What is self reference table in SQL?

Self-referencing table is a table that is a parent and a dependent in the same referential constraint. I. e. in such tables a foreign key constraint can reference columns within the same table.

What is a referencing key?

A key reference is a one-byte identifier that specifies a cryptographic key according to its PIV Key Type. The identifier is part of the cryptographic material used in a cryptographic protocol, such as an authentication or a signing protocol.


1 Answers

ALTER TABLE [SchemaName].[TableName]  WITH CHECK ADD  
CONSTRAINT [FK_TableName_TableName] FOREIGN KEY([Id])
REFERENCES [SchemaName].[TableName] ([Id])

This foreign key is completely redundant and pointless just delete it. It can never be violated as a row matches itself validating the constraint.

In a hierarchical table the relationship would be between two different columns (e.g. Id and ParentId)

As for why it may have been created quite likely through use of the visual designer if you right click the "Keys" node in object explorer and choose "New Foreign Key" then close the dialogue box without deleting the created foreign key and then make some other changes in the opened table designer and save it will create this sort of redundant constraint.

like image 62
Martin Smith Avatar answered Jan 01 '23 20:01

Martin Smith