liveBook · Manning

Unique constraint

As explained in Learn SQL in a Month of Lunches

A unique constraint is a database rule requiring non-null values in a column or column set to be distinct.

A unique constraint prevents duplicate non-null values in a column. If an inserted or updated value already appears in another row, the database reports an error. section 19.1.3

Keeping shipment tracking numbers distinct

A shipment table can declare TrackingNumber as UNIQUE. That rule ensures one tracking number is never assigned to two shipments, while a primary key still identifies each shipment row. section 19.1.3 section 18.3.2

CREATE TABLE shipment (
    ShipmentID int NOT NULL,
    OrderID int NOT NULL,
    ShipmentCost decimal(5,2) NOT NULL,
    ShipmentMethod char(1) NOT NULL,
    TrackingNumber varchar(20) NOT NULL UNIQUE,
    ShipmentDate datetime NOT NULL DEFAULT (CURRENT_DATE()),
    CONSTRAINT PK_shipment PRIMARY KEY (ShipmentID),
    CONSTRAINT FK_shipment_orderheader FOREIGN KEY (OrderID)
        REFERENCES orderheader(OrderID)
    );

This complete table definition applies a UNIQUE constraint directly to the required TrackingNumber column. section 19.1.3

Keep these differences in mind:

  • A table may have multiple UNIQUE constraints, but only one PRIMARY KEY constraint. section 19.1.3
  • UNIQUE constraints can allow NULL values; the permitted number varies by database system. section 19.1.3
  • A UNIQUE constraint may create an index automatically in MySQL, whereas other systems may require a separate index. section 19.3.2

How Learn SQL in a Month of Lunches covers it

How deep it goes
Explains declaration syntax, primary-key differences, NULL behavior, and related indexing, but does not detail composite UNIQUE definitions.
Examples
Uses shipment TrackingNumber declarations, duplicate-value errors, and a MySQL-created nonclustered index.
What you can do after
Build it from scratch by declaring a UNIQUE TrackingNumber column and anticipating duplicate-value and NULL-handling behavior.
How it connects
Connects unique constraints with primary keys, NULL values, nonclustered indexes, and database management systems.

Also explained in

Compare how 7 books explain unique constraint →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn SQL in a Month of Lunches. The section links point to the parts of the book it draws on.