
The following example creates a table and defines a primary key on the column CustomerID and a clustered index on TransactionID in the AdventureWorks database. , CONSTRAINT PK_TransactionHistoryArchive1_TransactionID PRIMARY KEY CLUSTERED (TransactionID)Ĭreate a primary key with clustered index in a new table TransactionID int IDENTITY (1,1) NOT NULL CREATE TABLE Production.TransactionHistoryArchive1 The following example creates a table and defines a primary key on the column TransactionID in the AdventureWorks database. ALTER TABLE Production.TransactionHistoryArchiveĪDD CONSTRAINT PK_TransactionHistoryArchive_TransactionID PRIMARY KEY CLUSTERED (TransactionID) The following example creates a primary key on the column TransactionID in the AdventureWorks database. Using Transact-SQL Create a primary key in an existing table For more information, see Modify Primary Keys. However, you can change the order of columns after the primary key is created.

If you define a compound key, the order of columns in the primary key matches the order of columns as shown in the table. If a primary key consists of more than one column, duplicate values are allowed in one column, but each combination of values from all the columns in the primary key must be unique. A message will warn you that existing relationships will be automatically deleted as part of this process.Ī primary key column is identified by a primary key symbol in its row selector. If you want to redefine the primary key, any relationships to the existing primary key must be deleted before the new primary key can be created. Right-click the row selector for the column and select Set Primary Key.If you want to select multiple columns, hold down the CTRL key while you click the row selectors for the other columns. In Table Designer, click the row selector for the database column you want to define as the primary key.In Object Explorer, right-click the table to which you want to add a unique constraint, and click Design.

Using SQL Server Management Studio Create a primary key If nullability is not specified, all columns participating in a PRIMARY KEY constraint have their nullability set to NOT NULL.Ĭreating a new table with a primary key requires CREATE TABLE permission in the database and ALTER permission on the schema in which the table is being created.Ĭreating a primary key in an existing table requires ALTER permission on the table. Before You Begin Limitations and RestrictionsĪ table can contain only one PRIMARY KEY constraint.Īll columns defined within a PRIMARY KEY constraint must be defined as NOT NULL. Creating a primary key automatically creates a corresponding unique clustered index, or a nonclustered index if specified as such. You can define a primary key in SQL Server by using SQL Server Management Studio or Transact-SQL. SQL Server 2016 (13.x) and later Azure SQL Database Azure SQL Managed Instance
