SQL Primary Key

A Primary Key is a column (or a set of columns) that uniquely identifies each row in a table. It cannot contain NULL values, and each value must be unique. Each table can only have one primary key.

Tutorials dojo strip

SQL Primary Key Syntax

When creating a table:

SQL

For composite keys (multiple columns):

SQL

SQLite does not support dropping primary keys directly using ALTER TABLE.

SQL Primary Key Example

SQL Primary Key on Create Table

This query sets up a table to store medical records with a unique record_id.

SQL

This query shows how to create a composite primary key using two columns.

SQL

SQL Primary Key on Alter Table

SQLite only supports adding a column using ALTER TABLE, but it doesn’t allow adding a primary key to an existing table. If you need to add a primary key to an existing table, you can follow this process:

This query creates a new table with a primary key:

SQL

This query copies the data from the old table into the new one:

SQL

Then, you would drop the original table and rename the new one:

SQL

SQL Primary Key Drop a Primary Key Constraint Example

SQLite does not support dropping a primary key using ALTER TABLE DROP CONSTRAINT. However, this is how it would normally look in standard SQL (like MySQL or SQL Server):

SQL

In SQLite, use the same workaround approach as above:

  1. Create a new version of the table without the primary key.
  2. Copy the data into it.
  3. Drop the old table.
  4. Rename the new one to match the original.

SQL Primary Key Labs

Tutorials dojo strip