SQL Reference

Quick Reference

The PRIMARY KEY keywords uniquely identifies each record in a table, which can have only one primary key consisting of a single field or multiple fields.

PRIMARY KEY on CREATE TABLE

The following creates a PRIMARY KEY on the customer_id column when the Customers table is created.

MySQL:

CREATE TABLE Customers (
    customer_id int NOT NULL,
    last_name varchar(255) NOT NULL,
    first_name varchar(255),
    PRIMARY KEY (customer_id)
);

SQL Server:

CREATE TABLE Customers (
    customer_id int NOT NULL PRIMARY KEY,
    last_name varchar(255) NOT NULL,
    first_name varchar(255)
);

The following creates a PRIMARY KEY on the customer_id and last_name columns when the Customers table is created. It is one PRIMARY KEY made up of two columns.

MySQL and SQL Server:

CREATE TABLE Customers (
    customer_id int NOT NULL,
    last_name varchar(255) NOT NULL,
    first_name varchar(255),
    CONSTRAINT pk_customer PRIMARY KEY (customer_id, last_name)
);

PRIMARY KEY on ALTER TABLE

The following creates a PRIMARY KEY on the customer_id column when the Customers table already exists.

MySQL and SQL: Server:

ALTER TABLE Customers
ADD PRIMARY KEY (customer_id);

The following creates a PRIMARY KEY on the customer_id and last_name columns when the Customers table already exists. It is one PRIMARY KEY made up of two columns.

MySQL and SQL Server:

ALTER TABLE Customers
ADD CONSTRAINT pk_customers PRIMARY KEY (customer_id, last_name);

Note

If you use the ALTER TABLE statement to add a primary key, the primary key column(s) must have already been declared to not contain NULL values when the table was first created.

DROP a PRIMARY KEY CONSTRAINT

MySQL:

ALTER TABLE Customers
DROP PRIMARY KEY;

SQL Server:

ALTER TABLE Customers
DROP CONSTRAINT pk_customer;

SQL Notes:

  • Any work being done to modify the structure of a database or delete tables or the the database itself should only be done after making a recent backup

We’d like to acknowledge that we learned a great deal of our coding from W3Schools and TutorialsPoint, borrowing heavily from their teaching process and excellent code examples. We highly recommend both sites to deepen your experience, and further your coding journey. We’re just hitting the basics here at 1SMARTchicken.