Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Primary and Foreign Key at the same time

Would it be possible in SQL Server 2008 to have a table created with 2 columns that are at the same time primary and foreign keys? If yes, how would such a code look like? I've searched and came up with nothing.

like image 249
Eduard Luca Avatar asked Jan 12 '12 21:01

Eduard Luca


People also ask

Can a key be primary and foreign at the same time?

A Foreign Key is used for referential integrity, to make sure that a value exists in another table. The Foreign key needs to reference the primary key in another table. If you want to have a foreign key that is also unique, you could make a FK constraint and add a unique index/constraint to that same field.

Can we have primary key and foreign key in same column?

Yes, it can.

Can an attribute be both primary and foreign key?

Yes. You would do this for instance if you wanted to enforce that all employees are users, and some users can be employees.

Can a FK be a PK?

Yes of course you can have PK and FK at the same time. PK & FK at the same time means that you want to index on the primary key, but at the same time you want to restrict the values of the PK based on values that exist in another attribute.


1 Answers

Sure, no problem:

CREATE TABLE dbo.[User] (   Id int NOT NULL IDENTITY PRIMARY KEY,   Name nvarchar(1024) NOT NULL );  CREATE TABLE [Group]  (   Id int NOT NULL IDENTITY PRIMARY KEY,   Name nvarchar(1024) NOT NULL );  CREATE TABLE [UserToGroup] (   UserId int NOT NULL,   GroupId int NOT NULL,   PRIMARY KEY CLUSTERED ( UserId, GroupId ),   FOREIGN KEY ( UserId ) REFERENCES [User] ( Id ) ON UPDATE  NO ACTION  ON DELETE  CASCADE,   FOREIGN KEY ( GroupId ) REFERENCES [Group] ( Id ) ON UPDATE  NO ACTION  ON DELETE  CASCADE ); 

This is quite commonly used to model many-to-many relations.

like image 94
Marnix van Valen Avatar answered Sep 19 '22 03:09

Marnix van Valen