Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create composite primary key in SQL Server 2008

People also ask

How do I add a composite primary key to an existing table in SQL?

You can create an index for composite primary key that uses the same fields present in your composite primary key. mysql> alter table new_orders ADD INDEX new_index (order_id, product_id); Hopefully, now you can create composite primary key in MySQL.

How do I create a composite unique key in SQL Server?

You can also create a Composite Unique Key consisting of two or more fields. To do that we need to apply the Unique Constraint on the table level. In the following example, we create a unique key consisting of FirstName & LastName . The FirstName & LastName themselves can contain duplicate values.


create table my_table (
     column_a integer not null,
     column_b integer not null,
     column_c varchar(50),
     primary key (column_a, column_b)
);

CREATE TABLE UserGroup
(
  [User_Id] INT NOT NULL,
  [Group_Id] INT NOT NULL

  CONSTRAINT PK_UserGroup PRIMARY KEY NONCLUSTERED ([User_Id], [Group_Id])
)

Via Enterprise Manager (SSMS)...

  • Right Click on the Table you wish to create the composite key on and select Design.
  • Highlight the columns you wish to form as a composite key
  • Right Click over those columns and Set Primary Key

To see the SQL you can then right click on the Table > Script Table As > Create To


I know I'm late to this party, but for an existing table, try:

ALTER table TABLE_NAME
ADD CONSTRAINT [name of your PK, e.g. PK_TableName] PRIMARY KEY CLUSTERED (column1, column2, etc.)