Foreign Keys in Microsoft SQL Server
Foreign Keys in Microsoft SQL Server
Foreign Keys in Microsoft SQL Server
database tables, so it can only be retrieved using a JOIN query which requires an existing
relationship between the tables.
When you look at the structure of the tables, the field defining the relationship is
probably obvious the Position ID field. Each employee can have only one position and
that position is identified by including the Position ID from the Positions tables
corresponding entry. In addition to being the primary key for the Positions table, in this
example, the Position ID field is also a foreign key from the Employees table to the
Positions table. The database can then use this field to correlate information from
multiple tables and ensure that any changes or additions to the database continue to
enforce referential integrity.
Once youve identified the foreign key, you can go ahead and pull the desired
information from the database using the following query:
SELECT FirstName, LastName, Title
FROM Employees INNER JOIN Positions
ON Employees.PositionID = Positions.PositionID
Positions(PositionID)
You may also create a foreign key when you create a table by adding the clause:
FOREIGN KEY REFERENCES Positions(PositionID)
to the end of the column definition for the foreign key column.