ADVERTISEMENT

SQL PRIMARY KEY

The PRIMARY KEY uniquely identifies each row in a table. It ensures no duplicate or NULL values exist in the key column(s).

🔹 Basic Syntax

-- Single column primary key
column_name data_type PRIMARY KEY;

-- Composite primary key (multiple columns)
PRIMARY KEY (column1, column2);

🔹 Example

CREATE TABLE employees (
  employee_id INT PRIMARY KEY,   -- unique ID, no NULLs
  first_name VARCHAR(50),
  last_name VARCHAR(50),
  email VARCHAR(100) UNIQUE
);

-- Composite key example
CREATE TABLE orders (
  order_id INT,
  product_id INT,
  quantity INT,
  PRIMARY KEY (order_id, product_id)  -- combination uniquely identifies each row
);

🔹 Important Notes

  • PRIMARY KEY columns must be UNIQUE and NOT NULL.
  • Each table can have only one PRIMARY KEY.
  • Primary key automatically creates a unique index for faster lookups.
  • Often used as a reference in FOREIGN KEY constraints.
  • If no primary key exists, it’s harder to uniquely identify rows and enforce data integrity.

🧠 Quick Recap

Key PointExplanation
PRIMARY KEYUniquely identifies each row, no duplicates or NULLs
Single or CompositeSupports one or multiple columns as key
Unique & NOT NULLEnforced automatically
One per tableOnly one primary key allowed per table
Index createdUnique index created for fast data retrieval

💡 Always define a PRIMARY KEY to ensure each record is uniquely identifiable and maintain data integrity.

ADVERTISEMENT