Lesson 1 of 3 Constraints and Sequences

Primary Key and Foreign Key Constraints

This lesson explains how primary and foreign keys enforce identity and referential integrity, the referential actions, and why foreign keys need indexes.

Learning outcomes

After completing this lesson, you will be able to:

  • Describe how a PRIMARY KEY is enforced and its relationship with the clustered index.
  • Choose a referential action for a parent-child relationship.
  • Explain the effect of missing foreign key indexes and untrusted constraints.

PRIMARY KEY constraints

A PRIMARY KEY constraint uniquely identifies each row: its columns cannot be NULL and cannot repeat, and a table has at most one. It is enforced by a unique index, clustered by default unless a clustered index already exists or NONCLUSTERED is specified. A surrogate key (an IDENTITY or sequence integer) is stable and narrow, while a natural key (such as an ISO country code) carries meaning; many designs use a surrogate primary key with a UNIQUE constraint on the natural key.

FOREIGN KEY constraints and referential actions

A FOREIGN KEY constraint requires that each non-NULL value in the child columns exists in the parent's primary key or unique constraint. Referential actions decide what happens when a parent row is deleted or its key is updated, as the following table explains.

ActionEffect on child rows
NO ACTION (default)The delete or update fails if child rows exist
CASCADEChild rows are deleted, or their foreign key values are updated
SET NULLChild foreign key columns are set to NULL (they must be nullable)
SET DEFAULTChild foreign key columns are set to their default values
CREATE TABLE Sales.OrderLines
(
    OrderID    int NOT NULL,
    LineNumber smallint NOT NULL,
    ProductID  int NOT NULL,
    Quantity   smallint NOT NULL,
    CONSTRAINT PK_OrderLines PRIMARY KEY (OrderID, LineNumber),
    CONSTRAINT FK_OrderLines_Orders FOREIGN KEY (OrderID)
        REFERENCES Sales.Orders (OrderID) ON DELETE CASCADE,
    CONSTRAINT FK_OrderLines_Products FOREIGN KEY (ProductID)
        REFERENCES Catalog.Product (ProductID)
);
CREATE INDEX IX_OrderLines_ProductID ON Sales.OrderLines (ProductID);
Match the pairs

Referential actions

Exam skills 1.1.4

Match each requirement with the referential action that meets it.

Log in to try this activity Interactive activities are free with an account.

Indexing and trust

SQL Server does not index foreign key columns automatically. Without an index, joins from parent to child and deletes of parent rows (which must check for children) scan the child table, which causes slow deletes and blocking. A constraint added or re-enabled WITH NOCHECK is not verified against existing rows and is marked untrusted (is_not_trusted = 1 in sys.foreign_keys), so the optimizer cannot use it to eliminate joins. ALTER TABLE ... WITH CHECK CHECK CONSTRAINT validates existing data and restores trust.

True or false

Foreign key trust

Exam skills 1.1.4

Decide whether each statement about foreign keys is true.

Log in to try this activity Interactive activities are free with an account.
Worked example

Deleting customers

When a customer requests account deletion, their orders and order lines must be removed in the same operation, while products that appear on those order lines must never be deleted through this path. Deleting a customer currently fails with a foreign key error and takes minutes on a large database. What should the developer configure?

Set ON DELETE CASCADE on the foreign keys from Orders to Customers and from OrderLines to Orders, keep NO ACTION on the foreign key from OrderLines to Products, and index the foreign key columns Orders.CustomerID and OrderLines.OrderID. Cascading removes the dependent rows in the same statement, and the indexes avoid scanning the child tables. Disabling the constraints would allow orphaned rows, and a trigger would duplicate what referential actions already do.

Check yourself

Does creating a FOREIGN KEY constraint create an index on the foreign key columns?

Show answer

No. They must be indexed explicitly to make joins and parent deletes efficient.

Exam Tips

Remember for the exam

  • Remove child rows with the parent: ON DELETE CASCADE.
  • Foreign key columns are not indexed automatically; index them.
  • WITH NOCHECK leaves a constraint untrusted for the optimizer.
  • One primary key per table; NULLs are not allowed in it.