SQL
HTML
CSS
JavaScript
jQuery
PHP
WordPress
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);
				
			

DROP a PRIMARY KEY CONSTRAINT

MySQL:

				
					ALTER TABLE Customers
DROP PRIMARY KEY;
				
			

SQL Server:

				
					ALTER TABLE Customers
DROP CONSTRAINT pk_customer;
				
			

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.

SQL
HTML
CSS
JavaScript
jQuery
PHP
WordPress

Why 1SMARTchicken?

This site was built and is maintained to benefit my autistic son.
See More →

My Son's Name is Johnny

He was diagnosed as autistic quite late, at age four...
His story

Buy Me a Coffee

Thanks for your support!

Feedback

If you see an error on the page or the code itself is incorrect or incomplete, or just plain wrong, please let us know. We’re always learning. NOTE: we do not sell your information and will not send you spam emails.