MySQL Constraints

Primary Key Constraint:

  • A primary key uniquely identifies each record in a table.
  • It ensures that each row in a table is uniquely identifiable.
  • Only one primary key can exist per table.
  • Commonly used for ID columns.
                      
CREATE TABLE table_name (
    id INT PRIMARY KEY,
    name VARCHAR(50)
);

                      
                    

Foreign Key Constraint:

  • A foreign key establishes a relationship between two tables.
  • It ensures referential integrity by enforcing that the value in a column matches the value in another table's primary key.
                      
CREATE TABLE orders (
    order_id INT PRIMARY KEY,
    customer_id INT,
    FOREIGN KEY (customer_id) REFERENCES customers(id)
);

                      
                    

Unique Constraint:

  • A unique constraint ensures that all values in a column are unique.
  • Unlike a primary key, multiple unique constraints can exist per table.
  • Useful for columns that should contain unique values but aren't primary keys.
                      
CREATE TABLE users (
    email VARCHAR(100) UNIQUE,
    username VARCHAR(50)
);