SQL Cookbook Lesson

How to remove a primary key in SQL

Learn how to remove a primary key in SQL with examples and explanations from SQLPad.

Problem

You have a table in your SQL database that has a primary key set. You want to know how to remove this primary key.

Sample data

Let's say we have a table "Employees" with columns "EmployeeID", "FirstName", "LastName", and "Email", where "EmployeeID" is the primary key.

CREATE TABLE Employees (
    EmployeeID int PRIMARY KEY,
    FirstName varchar(255),
    LastName varchar(255),
    Email varchar(255)
);

MySQL Solution

ALTER TABLE Employees
DROP PRIMARY KEY;

PostgreSQL Solution

In PostgreSQL, primary keys usually have a system-assigned name, so you have to know the name of the primary key constraint.

ALTER TABLE Employees
DROP CONSTRAINT Employees_pkey;

Explanation

MySQL

In MySQL, to remove a primary key from a table, you use the ALTER TABLE statement followed by the DROP PRIMARY KEY clause. This statement will remove the primary key from the table 'Employees'.

PostgreSQL

PostgreSQL works a bit differently. Instead of simply dropping the primary key, you have to drop the constraint that enforces the primary key. Constraints in PostgreSQL are usually named in the format tablename_pkey. Therefore, to drop the primary key on the 'Employees' table, you use the ALTER TABLE command followed by the DROP CONSTRAINT clause and the name of the primary key constraint. If you're not sure of the constraint's name, you can find it by inspecting the table's details or querying the information schema.

Keep Practicing

Related Cookbook Lessons

View all lessons

Interview Prep

Begin Your SQL, Python, and R Journey

Master 230 interview-style coding questions and build the data skills needed for analyst, scientist, and engineering roles.