Adds a primary key to an existing table that doesn't have a primary key.


Add-PrimaryKey [-TableName] <String> [-SchemaName <String>] [-ColumnName] <String[]> [-NonClustered] [-Option <String[]>] [-Name <String>] [<CommonParameters>]


Adds a primary key to a table. If the table already has a primary key, make sure to remove it with Remove-PrimaryKey.

Related Commands


Name Type Description Required? Pipeline Input Default Value
TableName String

The name of the table.

true false
SchemaName String

The schema name of the table. Defaults to dbo.

false false dbo
ColumnName String[]

The column(s) that should be part of the primary key.

true false
NonClustered SwitchParameter

Create a non-clustered primary key.

false false False
Option String[]

An array of primary key options.

false false
Name String

The name for the . If not given, a sensible name will be created.

false false


Add-PrimaryKey -TableName Cars -ColumnName Year,Make,Model

Adds a primary key to the Cars table on the Year, Make, and Model columns.


Add-PrimaryKey -TableName Cars -ColumnName Year,Make,Model -NonClustered -Option 'IGNORE_DUP_KEY = ON','DROP_EXISTING=ON'

Demonstrates how to create a non-clustered primary key, with some index options.