"No primary or candidate keys in the referenced table" (Msg 1776)

SQL Server error 1776, no primary or candidate keys in the referenced table, means a foreign key points at columns that are not a key. The fixes, with SQL.

What SQL Server is telling you

You create a foreign key and SQL Server stops with two messages:

Msg 1776, Level 16, State 1, Line 5
There are no primary or candidate keys in the referenced table 'dbo.Member' that match the referencing column list in the foreign key 'FK_MemberNote_Member_Email'.
Msg 1750, Level 16, State 1, Line 5
Could not create constraint or index. See previous errors.

Here is a script that raises them. Each note names its member by email:

CREATE TABLE dbo.Member (
  MemberId int NOT NULL CONSTRAINT PK_Member PRIMARY KEY,
  Email    nvarchar(254) NOT NULL
);
CREATE TABLE dbo.MemberNote (
  MemberNoteId int NOT NULL
    CONSTRAINT PK_MemberNote PRIMARY KEY,
  Email        nvarchar(254) NOT NULL,
  Body         nvarchar(max) NOT NULL,
  CONSTRAINT FK_MemberNote_Member_Email FOREIGN KEY (Email)
    REFERENCES dbo.Member (Email)
);
dbo.Member with primary key MemberId and an Email column; dbo.MemberNote with an Email column; no line between them.
No line between them: ERDsmith doesn't let you make a foreign key with no key to point at.

Msg 1750 only reports the result: the constraint was not created. Msg 1776 is the cause, and it names both ends, the referenced table (dbo.Member) and the foreign key (FK_MemberNote_Member_Email, a name built from the child, the parent and the column, as the database naming conventions post lays out). The error also ends the batch. In this run dbo.Member exists afterwards, dbo.MemberNote does not, and any statement after it in the same batch never ran.

What counts as a candidate key

A foreign key must point at a candidate key: columns that uniquely identify each row, because the parent table declares them unique. SQL Server accepts three kinds:

  • the primary key;
  • a unique constraint;
  • a unique index without a WHERE filter. One with INCLUDE columns works; a filtered one raises the same error.

The referenced columns may allow NULL, as long as a unique constraint covers them. What doesn’t count is data that just happens to be unique, or an ordinary index. dbo.Member.Email in the script above is neither a key nor unique. Your emails may well be unique today, but nothing stops a second member from taking the same address tomorrow, and then a note would belong to two members. A foreign key can’t point at a column like that.

If you’re sure the table does have a key, list the ones SQL Server sees: every unique, unfiltered index on the parent, with its key columns in order. Primary keys and unique constraints are indexes too, so they show up here:

SELECT i.name AS KeyName, c.name AS ColumnName,
  ic.key_ordinal AS Position
FROM sys.indexes AS i
JOIN sys.index_columns AS ic
  ON ic.object_id = i.object_id AND ic.index_id = i.index_id
JOIN sys.columns AS c
  ON c.object_id = ic.object_id AND c.column_id = ic.column_id
WHERE i.object_id = OBJECT_ID('dbo.Member')
  AND i.is_unique = 1 AND i.has_filter = 0
  AND ic.key_ordinal > 0
ORDER BY i.name, ic.key_ordinal;

For dbo.Member it returns one row, PK_Member on MemberId. Email isn’t in any of them, so a foreign key on Email has nothing to match. A foreign key’s column list must match one of these keys exactly: the same columns, in the same order.

There are three ways out. Which one fits depends on what the child should hold.

Fix 1: reference the primary key

Usually the right fix. The child stores the parent’s primary key, not the email:

CREATE TABLE dbo.MemberNote (
  MemberNoteId int NOT NULL
    CONSTRAINT PK_MemberNote PRIMARY KEY,
  MemberId     int NOT NULL,
  Body         nvarchar(max) NOT NULL,
  CONSTRAINT FK_MemberNote_Member_MemberId
    FOREIGN KEY (MemberId)
    REFERENCES dbo.Member (MemberId)
);
dbo.Member with primary key MemberId and an Email column; dbo.MemberNote with foreign key MemberId, a line from Member to MemberNote.
The line runs from the primary key: one member, zero or more notes.

A member who changes address now changes one row in dbo.Member and no notes. The join runs on a 4-byte int instead of an nvarchar(254) that can take 508 bytes. If you want the email in a query on notes, join to dbo.Member for it.

Fix 2: declare the column unique

Sometimes the child really should hold the email: the notes come from a system that only knows members by address, say. Then tell SQL Server what you already believe, with a unique constraint, and the original foreign key works as written:

ALTER TABLE dbo.Member
  ADD CONSTRAINT AK_Member_Email UNIQUE (Email);
dbo.Member with primary key MemberId and alternate key Email; dbo.MemberNote with foreign key Email, a line from Member to MemberNote.
Email is now marked AK, and the original foreign key has a key to point at.

A unique constraint like this one is the table’s alternate key: a second way to name one row. The key query from above now returns AK_Member_Email on Email beside PK_Member. The cost is Fix 1’s benefit in reverse: changing the address of a member who has notes now fails with Msg 547, a conflict with FK_MemberNote_Member_Email, unless the foreign key says ON UPDATE CASCADE.

If the table already has two members with the same address, the constraint can’t be built:

Msg 1505, Level 16, State 1, Line 1
The CREATE UNIQUE INDEX statement terminated because a duplicate key was found for the object name 'dbo.Member' and the index name 'AK_Member_Email'. The duplicate key value is (ana@example.com).
Msg 1750, Level 16, State 1, Line 1
Could not create constraint or index. See previous errors.
The statement has been terminated.

Find the duplicates first, decide which row each pair keeps, then add the constraint:

SELECT Email, COUNT(*) AS Members
FROM dbo.Member
GROUP BY Email
HAVING COUNT(*) > 1;

Fix 3: reference the whole key, in its order

With a composite key, the foreign key has to list every column of it. A session here is a workshop’s code and a number, so a booking that keeps only the number points at no key:

CREATE TABLE dbo.Session (
  WorkshopCode char(4)      NOT NULL,
  SessionNo    int          NOT NULL,
  StartsAt     datetime2(0) NOT NULL,
  CONSTRAINT PK_Session PRIMARY KEY (WorkshopCode, SessionNo)
);
CREATE TABLE dbo.Booking (
  SessionNo int NOT NULL,
  MemberId  int NOT NULL,
  CONSTRAINT PK_Booking PRIMARY KEY (SessionNo, MemberId),
  CONSTRAINT FK_Booking_Session_SessionNo
    FOREIGN KEY (SessionNo)
    REFERENCES dbo.Session (SessionNo)
);
dbo.Session with primary key WorkshopCode and SessionNo; dbo.Booking with primary key SessionNo and MemberId; no line between them.
No line again: a relationship to dbo.Session carries its whole key, or there is none.

SQL Server answers with Msg 1776 for dbo.Session and FK_Booking_Session_SessionNo. Two near misses raise it too: listing both columns in another order, (SessionNo, WorkshopCode) on both sides, and adding a column the key doesn’t have, such as StartsAt. The column list has to be the key itself, in the key’s order:

CREATE TABLE dbo.Booking (
  WorkshopCode char(4) NOT NULL,
  SessionNo    int     NOT NULL,
  MemberId     int     NOT NULL,
  CONSTRAINT PK_Booking
    PRIMARY KEY (WorkshopCode, SessionNo, MemberId),
  CONSTRAINT FK_Booking_Session_WorkshopCode_SessionNo
    FOREIGN KEY (WorkshopCode, SessionNo)
    REFERENCES dbo.Session (WorkshopCode, SessionNo)
);
dbo.Session with primary key WorkshopCode and SessionNo; dbo.Booking with WorkshopCode and SessionNo as primary and foreign key columns, and MemberId; a line from Session to Booking.
Both key columns travel into dbo.Booking, in the key's order.

When the key comes later in the script

The key can exist and still be too late. In this script the primary key of dbo.Workshop is added after the foreign key that needs it:

CREATE TABLE dbo.Workshop (
  WorkshopCode char(4)      NOT NULL,
  Title        nvarchar(80) NOT NULL
);
CREATE TABLE dbo.Lesson (
  LessonId     int     NOT NULL
    CONSTRAINT PK_Lesson PRIMARY KEY,
  WorkshopCode char(4) NOT NULL CONSTRAINT FK_Lesson_Workshop
    REFERENCES dbo.Workshop (WorkshopCode)
);
ALTER TABLE dbo.Workshop
  ADD CONSTRAINT PK_Workshop PRIMARY KEY (WorkshopCode);
dbo.Workshop alone, with an empty primary key and a warning mark; no dbo.Lesson.
Drawn as SQL Server leaves it: the batch ends at the failing foreign key, so dbo.Lesson is never created and dbo.Workshop has no key.

The foreign key fails with Msg 1776, the batch ends there, and the ALTER TABLE never runs: dbo.Workshop is left without its primary key. Create every key before the foreign keys that reference it, or put the key inside its CREATE TABLE.

How ERDsmith helps

SQL Server raises Msg 1776 at CREATE TABLE or ALTER TABLE time, after the email column, the half-copied session key or the late ALTER TABLE is already written. Every broken script above has a diagram with no line, because in ERDsmith you design the schema first, and this mistake can’t be made there:

  • A relationship points at the parent’s primary key or a unique index / alternate key you pick. There is no way to point it at a column like dbo.Member.Email before it has a key.
  • ERDsmith makes the child’s foreign key columns for you, every column of the key in its order, so dbo.Booking gets both WorkshopCode and SessionNo, and keeps their names and types in step with the parent’s.
  • A key or index left with no columns shows in the Output as a problem until it has some.