Primary key vs foreign key: the difference, in SQL Server

Primary key vs foreign key: a primary key uniquely identifies each row of its table, a foreign key points at it from another. What SQL Server checks on each.

What is the difference between a primary key and a foreign key?

A primary key uniquely identifies each row of its table: no two rows share a value, and no row leaves it empty. A foreign key is a column in another table that holds those values, so each of its rows points at one row of the first table. The primary key says “this is reader 1”. The foreign key says “this loan belongs to reader 1”.

A small library has both; the library management system template holds the full design. Every reader and every book has a primary key, and a loan records which book went to which reader by holding the two keys:

CREATE TABLE dbo.Reader (
  ReaderId int NOT NULL CONSTRAINT PK_Reader PRIMARY KEY,
  Email    nvarchar(254) NOT NULL,
  FullName nvarchar(100) NOT NULL
);
CREATE TABLE dbo.Book (
  BookId int NOT NULL CONSTRAINT PK_Book PRIMARY KEY,
  Isbn   char(13)      NOT NULL,
  Title  nvarchar(200) NOT NULL
);
CREATE TABLE dbo.Loan (
  LoanId     int  NOT NULL CONSTRAINT PK_Loan PRIMARY KEY,
  BookId     int  NOT NULL,
  ReaderId   int  NOT NULL,
  LoanedOn   date NOT NULL,
  ReturnedOn date NULL,
  CONSTRAINT FK_Loan_Book_BookId FOREIGN KEY (BookId)
    REFERENCES dbo.Book (BookId),
  CONSTRAINT FK_Loan_Reader_ReaderId FOREIGN KEY (ReaderId)
    REFERENCES dbo.Reader (ReaderId)
);
dbo.Book with primary key BookId and dbo.Reader with primary key ReaderId; dbo.Loan with primary key LoanId and foreign keys BookId and ReaderId; a line from Book to Loan and a line from Reader to Loan.
Each line runs from a primary key to the foreign key that holds its values: one reader, zero or more loans.

dbo.Loan carries three keys. LoanId is its own primary key. BookId and ReaderId are foreign keys, and their values come from dbo.Book and dbo.Reader. The table with the primary key is the parent; the table with the foreign key is the child.

The other differences, one per line:

  • A table has one primary key, and as many foreign keys as it has parents.
  • A primary key value never repeats. A foreign key value repeats as often as the child needs it, since one reader has many loans.
  • A primary key column is never NULL. A foreign key column may allow NULL, and a NULL is not checked against the parent.
  • SQL Server builds a unique index for a primary key, clustered unless the table already has a clustered one. It builds none for a foreign key.
  • A foreign key references the parent’s primary key, or other columns the parent declares unique. Anything else fails with Msg 1776.

Each point below is a run on SQL Server, with the messages it printed.

What SQL Server checks on a primary key

Readers go in with ReaderId as their key. The first insert works; the second reuses the key, and the third leaves it out:

INSERT INTO dbo.Reader (ReaderId, Email, FullName)
VALUES (1, N'ana@example.com', N'Ana Lima');
INSERT INTO dbo.Reader (ReaderId, Email, FullName)
VALUES (1, N'ben@example.com', N'Ben Okafor');
INSERT INTO dbo.Reader (ReaderId, Email, FullName)
VALUES (NULL, N'cy@example.com', N'Cy Park');
Msg 2627, Level 14, State 1, Line 3
Violation of PRIMARY KEY constraint 'PK_Reader'. Cannot insert duplicate key in object 'dbo.Reader'. The duplicate key value is (1).
The statement has been terminated.
Msg 515, Level 16, State 2, Line 5
Cannot insert the value NULL into column 'ReaderId', table 'Library.dbo.Reader'; column does not allow nulls. INSERT fails.
The statement has been terminated.

Msg 2627 names the constraint, the table and the value that clashed. Msg 515 comes from the column, not the constraint: SQL Server made ReaderId NOT NULL when it joined the primary key, because every primary key column must be NOT NULL. Declare one NULL on purpose and the CREATE TABLE fails with Msg 8111, “Cannot define PRIMARY KEY constraint on nullable column”.

Both errors end only their own statement. The first reader stays, and a statement after the failed ones still runs.

A second primary key isn’t possible either. Adding one on Email fails with Msg 1779, “Table ‘Reader’ already has a primary key defined on it.” If emails must be unique too, that is a unique constraint: the table’s alternate key.

What SQL Server checks on a foreign key

The foreign key watches both tables. With reader 1 in place, a book and two loans go in, then a loan for a reader who doesn’t exist, then an attempt to delete reader 1:

INSERT INTO dbo.Book (BookId, Isbn, Title)
VALUES (10, '9780131103627', N'The C Programming Language');
INSERT INTO dbo.Loan (LoanId, BookId, ReaderId, LoanedOn)
VALUES (100, 10, 1, '2026-03-02'),
       (101, 10, 1, '2026-04-06');
INSERT INTO dbo.Loan (LoanId, BookId, ReaderId, LoanedOn)
VALUES (102, 10, 7, '2026-04-07');
DELETE FROM dbo.Reader WHERE ReaderId = 1;
Msg 547, Level 16, State 1, Line 6
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Loan_Reader_ReaderId". The conflict occurred in database "Library", table "dbo.Reader", column 'ReaderId'.
The statement has been terminated.
Msg 547, Level 16, State 1, Line 8
The DELETE statement conflicted with the REFERENCE constraint "FK_Loan_Reader_ReaderId". The conflict occurred in database "Library", table "dbo.Loan", column 'ReaderId'.
The statement has been terminated.

The two loans for reader 1 are fine. The loan for reader 7 fails, because no dbo.Reader row has that key. The delete fails for the opposite reason: two loans still point at reader 1, and removing it would leave them pointing at nothing.

Both failures are Msg 547, worded from each side; the INSERT statement conflicted with the FOREIGN KEY constraint goes through the insert’s causes. An insert or update in the child names the FOREIGN KEY constraint and the parent table; a delete or key change in the parent names the REFERENCE constraint and the child table. Either way, the parent row has to exist first and leave last.

That last part is the foreign key’s default action, NO ACTION. A foreign key can say ON DELETE CASCADE instead, and the loans go with their reader, or ON DELETE SET NULL, and the loans stay with ReaderId emptied, which needs a nullable column. Microsoft’s page on cascading referential integrity lists all four actions. ON DELETE CASCADE shows when each action fits and what SQL Server refuses.

A NULL in a nullable foreign key column is never checked against the parent. That is how you write an optional relationship: a column that either names a parent row or names none.

Why the foreign key must match the key’s type

The foreign key column holds the parent’s values, so it has to be the parent’s type. Make it wider to be safe, and the foreign key won’t build:

CREATE TABLE dbo.Reader (
  ReaderId int NOT NULL CONSTRAINT PK_Reader PRIMARY KEY,
  FullName nvarchar(100) NOT NULL
);
CREATE TABLE dbo.Loan (
  LoanId   int    NOT NULL CONSTRAINT PK_Loan PRIMARY KEY,
  ReaderId bigint NOT NULL,
  LoanedOn date   NOT NULL,
  CONSTRAINT FK_Loan_Reader_ReaderId FOREIGN KEY (ReaderId)
    REFERENCES dbo.Reader (ReaderId)
);
dbo.Loan with a ReaderId column of type bigint and dbo.Reader with primary key ReaderId of type int; no line between them.
No line: ReaderId is bigint in dbo.Loan and int in dbo.Reader, and ERDsmith never builds a foreign key whose column types differ.
Msg 1778, Level 16, State 1, Line 5
Column 'dbo.Reader.ReaderId' is not the same data type as referencing column 'Loan.ReaderId' in foreign key 'FK_Loan_Reader_ReaderId'.
Msg 1750, Level 16, State 1, Line 5
Could not create constraint or index. See previous errors.

SQL Server compares the types exactly. bigint against int fails with Msg 1778, although every int fits in a bigint, and so does varchar(13) against char(13). The same type with another length, such as char(10) against char(13), fails with Msg 1753.

The error also ends the batch: dbo.Reader exists afterwards, dbo.Loan does not. The fix is to declare Loan.ReaderId as int, as in the first script.

Can a column be both a primary key and a foreign key?

Yes, and it is common. A book can have several authors and an author several books, so the link between them gets a table of its own, whose primary key is made of two foreign keys:

CREATE TABLE dbo.Author (
  AuthorId int NOT NULL CONSTRAINT PK_Author PRIMARY KEY,
  FullName nvarchar(100) NOT NULL
);
CREATE TABLE dbo.BookAuthor (
  BookId   int NOT NULL,
  AuthorId int NOT NULL,
  CONSTRAINT PK_BookAuthor PRIMARY KEY (BookId, AuthorId),
  CONSTRAINT FK_BookAuthor_Book_BookId FOREIGN KEY (BookId)
    REFERENCES dbo.Book (BookId),
  CONSTRAINT FK_BookAuthor_Author_AuthorId
    FOREIGN KEY (AuthorId)
    REFERENCES dbo.Author (AuthorId)
);
dbo.Author with primary key AuthorId and dbo.Book with primary key BookId; dbo.BookAuthor whose primary key BookId and AuthorId are also its foreign keys; solid lines from Author and from Book to BookAuthor.
Solid lines and a rounded box: BookId and AuthorId are both the primary key of dbo.BookAuthor and its foreign keys.

Each column of dbo.BookAuthor plays both parts. As foreign keys, BookId must name a real book and AuthorId a real author. As the primary key, the pair must be unique, so one author can’t be listed twice on the same book. Neither column is unique alone: a book with three authors repeats its BookId three times.

Foreign key columns inside the child’s primary key make a relationship identifying, a solid line , and the pair is a composite key.

Can a foreign key reference its own table?

Yes. A reader who joined on a friend’s word can record that friend, and the friend is a reader too. The foreign key sits in dbo.Reader and references dbo.Reader’s own primary key:

ALTER TABLE dbo.Reader ADD ReferredById int NULL
  CONSTRAINT FK_Reader_Reader_ReferredById
    REFERENCES dbo.Reader (ReaderId);
dbo.Reader with primary key ReaderId and foreign key ReferredById; a line from dbo.Reader back to dbo.Reader; dbo.Book and dbo.Reader with their lines to dbo.Loan as before.
The line leaves dbo.Reader and comes back to it. ERDsmith writes the column as ReferredById.ReaderId: its name, then the key it holds.

The column allows NULL, because the first reader has nobody to name. Ana, already in the table, gets NULL when the column arrives, and a NULL isn’t checked. Then Ben joins on Ana’s word, and Cy names a reader 9:

INSERT INTO dbo.Reader (ReaderId, Email, FullName, ReferredById)
VALUES (2, N'ben@example.com', N'Ben Okafor', 1);
INSERT INTO dbo.Reader (ReaderId, Email, FullName, ReferredById)
VALUES (3, N'cy@example.com', N'Cy Park', 9);
SELECT ReaderId, ReferredById FROM dbo.Reader;
Msg 547, Level 16, State 1, Line 3
The INSERT statement conflicted with the FOREIGN KEY SAME TABLE constraint "FK_Reader_Reader_ReferredById". The conflict occurred in database "Library", table "dbo.Reader", column 'ReaderId'.
The statement has been terminated.

Ben’s row goes in. Cy’s fails with Msg 547, the same check as before, now on a FOREIGN KEY SAME TABLE constraint. The SELECT finds two readers: 1 with no referrer, 2 referred by 1.

A self-reference can’t cascade. The same foreign key with ON DELETE CASCADE fails with Msg 1785, “may cause cycles or multiple cascade paths”. So it stays NO ACTION, and a reader who referred others can’t be deleted while their rows still point at them.

Does SQL Server index a foreign key?

No. The primary key comes with an index; the foreign key doesn’t. After the first script, dbo.Loan has one index, PK_Loan, clustered and unique, and nothing on BookId or ReaderId:

SELECT name, type_desc, is_unique
FROM sys.indexes
WHERE object_id = OBJECT_ID('dbo.Loan');

CREATE INDEX IX_Loan_ReaderId ON dbo.Loan (ReaderId);
CREATE INDEX IX_Loan_BookId ON dbo.Loan (BookId);

Without an index on Loan.ReaderId, a query for one reader’s loans scans the whole of dbo.Loan. So does deleting a reader: SQL Server looks for loans that still point at the reader, and the delete’s plan shows a clustered index scan of dbo.Loan for it. Microsoft gives the same two reasons for indexing a foreign key. The two CREATE INDEX statements above add them.

A foreign key that leads the child’s primary key already has its index: in dbo.BookAuthor, BookId is the first column of PK_BookAuthor. AuthorId, second in that key, still needs one of its own if you look up an author’s books.

How ERDsmith helps

The bigint loan column reached SQL Server before Msg 1778 ended its batch, and a cascade on ReferredById would reach it before Msg 1785. Both mistakes can be caught on the diagram, and ERDsmith catches them there:

  • Every table has exactly one primary key, and its columns are NOT NULL.
  • A foreign key column gets its parent column’s type, length and collation, one column per parent key column in key order, and follows the key when its type changes. A script whose column differs in type, length, precision or scale, as the bigint one does, is drawn without that line, the foreign key SQL Server refuses with Msg 1778 or Msg 1753; a collation that differs is drawn and marked as an error, as SQL Server refuses it with Msg 1757.
  • A line from a table to itself gives it a column named after the key with Parent in front (ParentReaderId), stays non-identifying, and a cascade on it is marked as an error.