Setting Primary Key in Database Tables

When creating database tables, you can set primary keys in the following ways:

  1. To use a primary key constraint, when creating a table, you can add a PRIMARY KEY constraint after the column that needs to be designated as the primary key. For example:
CREATE TABLE employees (
    employee_id INT PRIMARY KEY,
    first_name VARCHAR(50),
    last_name VARCHAR(50)
);
  1. We can use auto-increment primary keys by using the AUTO_INCREMENT or SERIAL keyword to let the database generate primary key values automatically. For example:
CREATE TABLE employees (
    employee_id INT AUTO_INCREMENT PRIMARY KEY,
    first_name VARCHAR(50),
    last_name VARCHAR(50)
);
  1. Using composite keys: multiple columns can be combined to form a primary key. For example:
CREATE TABLE employees (
    employee_id INT,
    department_id INT,
    PRIMARY KEY (employee_id, department_id)
);

No matter which way you choose to set the primary key, you can ensure the uniqueness of each row of data in the table and improve the efficiency of data retrieval.

bannerAds