How to add primary key to existing table in SQL Server
By FoxLearn 7/2/2024 4:08:10 AM 323
First, Open your SQL Server Management Studio (SSMS) and connect to your database, then navigate to the database that contains the table you want to modify.
Next, Expand the database and locate the table in Object Explorer, then right-click on the table and select Design.
In the design view, select the column(s) you want to include in the primary key by ctrl + clicking on the key icon next to the columns, then set them as the primary key.
After defining the primary key columns, save the changes by clicking the Save icon in the toolbar or by pressing Ctrl + S
.
If you prefer using SQL scripts to modify your database.
ALTER TABLE TableName ADD CONSTRAINT PK_ConstraintName PRIMARY KEY (Column1, Column2, ...);
Suppose you have a table named Customers
and you want to add a primary key on the CustomerID
column.
ALTER TABLE Customers ADD CONSTRAINT PK_Customers PRIMARY KEY (CustomerID);
This script adds a primary key constraint named PK_Customers
on the CustomerID
column in the Customers
table.
- How to fix 'The transaction log for the database is null due to OLDEST_PAGE'
- How to convert varchar to uniqueidentifier in SQL Server
- How to convert timestamp to date in SQL Server
- How to Download and Restore Northwind database to SQL Server
- How to Download Microsoft SQL Server
- Saving changes is not permitted in SQL Server
- How to change ‘Edit Top 200 Rows’ and ‘Select Top 1000 Rows’ in SQL
- How to fix 'The specified sa password does not meet strong password requirements'