Sobes.tech
Junior

What is a primary key?

sobes.tech AI

Answer from AI

A primary key is a column or a set of columns in a database table that uniquely identifies each row in that table.

Main characteristics:

  • Uniqueness: The primary key values must be unique for each row.
  • Not null (NOT NULL): The primary key value cannot be NULL.
  • One per table: Each table can have only one primary key.
  • Indexing: When creating a primary key, the database automatically creates an index for it to improve search and join performance.

Example:

In the users table, the primary key can be the id column:

CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY, // Defining the primary key
    username VARCHAR(255) NOT NULL UNIQUE,
    email VARCHAR(255) NOT NULL UNIQUE
);

Uses of primary key:

  • Record identification
  • Linking tables through foreign keys
  • Ensuring data integrity
What is a primary key? — PHP - sobes.tech