The Daily WTF
Follow
CodeSOD: Only Create Me if I Exist
Foreign keys are crucial for connecting entities in relational databases and ensuring correct querying, aiding in data normalization. A common example is an order line table referencing a products table for sold items. Another frequent pattern involves hierarchical data, like an employee table with a ManagerId foreign key pointing back to itself. While foreign keys are widely used, they can still lead to issues. Roman shared an example of a foreign key constraint in the ListingDetails table where the Id field references itself. This configuration intentionally creates a self-referencing foreign key. Roman expressed surprise that SQL Server permits such a definition. The system allows this because a record naturally satisfies its own constraint. Essentially, this type of self-referencing foreign key acts as a no-operation. It's up to the developer to avoid such problematic configurations rather than the database system preventing all potential errors.