How To Add A Primary Key In Sql in SQL
How to Add a Primary Key in SQL
You can add a Primary Key to a table either when creating the table or after the table is created.
1. Adding Primary Key When Creating a Table
CREATE TABLE employees ( employee_id INT, name VARCHAR(50), PRIMARY KEY (employee_id));2. Adding Primary Key to an Existing Table
Syntax:
ALTER TABLE table_nameADD CONSTRAINT constraint_name PRIMARY KEY (column_name);Example:
ALTER TABLE employeesADD CONSTRAINT pk_employee_id PRIMARY KEY (employee_id);Notes:
The column(s) you use as a primary key must be UNIQUE and NOT NULL.
If the column already contains duplicates or NULLs, the DBMS will throw an error.
You can define a primary key on single or multiple columns (composite key):
ALTER TABLE ordersADD CONSTRAINT pk_order PRIMARY KEY (order_id, product_id);If you want me to write the exact syntax for a specific SQL database (MySQL, PostgreSQL, SQL Server, Oracle), just ask!