Golang Tutorials - Learn Go Programming with Easy Step-by-Step Guides

Explore comprehensive Golang tutorials for beginners and advanced programmers. Learn Go programming with easy-to-follow, step-by-step guides, examples, and practical tips to master Go language quickly.

How To Add A Primary Key In Sql in SQL

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!

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql
postgresql
mariaDB
sql