Sobes.tech
Junior — Middle

What restrictions exist for defining a primary key in an SQL database table?

sobes.tech AI

Answer from AI

Constraints for defining a primary key (PRIMARY KEY) in an SQL table:

  • Uniqueness: Values in the primary key column(s) must be unique for each row.
  • NULLs not allowed: The primary key column(s) cannot contain NULL values.
  • One primary key per table: A table can have only one primary key, but it can consist of multiple columns (composite key).
  • Data types: Usually, the primary key is chosen from data types that support comparison and indexing (e.g., integers, strings), but technically, there are few restrictions on the type.

Example of defining a primary key:

CREATE TABLE users (
    id INT PRIMARY KEY,
    username VARCHAR(50) NOT NULL,
    email VARCHAR(100)
);

Or a composite key:

CREATE TABLE orders (
    order_id INT,
    product_id INT,
    PRIMARY KEY (order_id, product_id)
);
What restrictions exist for defining a primary key in… - sobes.tech