DATABASE – Three ways to add a primary key

Create the primary key column in the column specification with an auto-assigned constraint name

CREATE TABLE customers (
    customer_id char(5) NOT NULL PRIMARY KEY,
    company     varchar(100),
    address     varchar(100),
    city        varchar(50),
    state       char(2),
    zip         char(5)
);

Add the primary key constraint when creating the table with a namable constraint

CREATE TABLE customers (
    customer_id char(5) NOT NULL,
    company     varchar(100),
    address     varchar(100),
    city        varchar(50),
    state       char(2),
    zip         char(5),
    CONSTRAINT PK_Customers_CustomerID PRIMARY KEY (customer_id)
);

Add the primary key after the table is created

CREATE TABLE customers (
    customer_id char(5) NOT NULL,
    company     varchar(100),
    address     varchar(100),
    city        varchar(50),
    state       char(2),
    zip         char(5)
);

ALTER TABLE customers
   ADD CONSTRAINT PK_Customers_CustomerID PRIMARY KEY (customer_id);

Leave a Reply

Your email address will not be published. Required fields are marked *