MySQL PRIMARY KEY Constraint

The PRIMARY KEY constraint uniquely identifies each record in a table. A table can only have one primary key, which can consist of single or multiple columns.

Example with Tamil Kings

CREATE TABLE tamil_kings_primary_key (
    id INT AUTO_INCREMENT PRIMARY KEY,
    king_name VARCHAR(100) NOT NULL,
    reign_period VARCHAR(50)
);

Code Explanation: The id column is the primary key, uniquely identifying each record in the tamil_kings_primary_key table.

Best Practices

  • Always define a primary key for each table to ensure data integrity.
  • Use AUTO_INCREMENT for numeric primary keys if possible.

Key Takeaways

  • A primary key must contain unique and non-null values.
  • It is used to identify each record in a table uniquely.