How to create composite primary key in SQL Server 2008 - sql

I want to create tables in SQL Server 2008, but I don't know how to create composite primary key. How can I achieve this?

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.)

For MSSQL Server 2012
CREATE TABLE usrgroup(
usr_id int FOREIGN KEY REFERENCES users(id),
grp_id int FOREIGN KEY REFERENCES groups(id),
PRIMARY KEY (usr_id, grp_id)
)
UPDATE
I should add !
If you want to add foreign / primary keys altering, firstly you should create the keys with constraints or you can not make changes. Like this below:
CREATE TABLE usrgroup(
usr_id int,
grp_id int,
CONSTRAINT FK_usrgroup_usrid FOREIGN KEY (usr_id) REFERENCES users(id),
CONSTRAINT FK_usrgroup_groupid FOREIGN KEY (grp_id) REFERENCES groups(id),
CONSTRAINT PK_usrgroup PRIMARY KEY (usr_id,grp_id)
)
Actually last way is healthier and serial. You can look the FK/PK Constraint names (dbo.dbname > Keys > ..) but if you do not use a constraint, MSSQL auto-creates random FK/PK names. You will need to look at every change (alter table) you need.
I recommend that you set a standard for yourself; the constraint should be defined according to the your standard. You will not have to memorize and you will not have to think too long. In short, you work faster.

First create the database and table, manually adding the columns. In which column to be primary key. You should right click this column and set primary key and set the seed value of the primary key.

To create a composite unique key on table
ALTER TABLE [TableName] ADD UNIQUE ([Column1], [Column2], [column3]);

CREATE TABLE UserGroup
(
[User_Id] INT Foreign Key,
[Group_Id] INT foreign key,
PRIMARY KEY ([User_Id], [Group_Id])
)

Related

Condition for some column in foreign key

There is table A with columns (Id, BId). BId is foreign key to table B. B has columns (Id, Type).
CREATE TABLE [A] (
[Id] INT IDENTITY CONSTRAINT [PK_A_Id] PRIMARY KEY,
[BId] INT NOT NULL CONSTRAINT [FK_A_B] REFERENCES [B](Id)
)
GO
CREATE TABLE [B] (
[Id] INT IDENTITY CONSTRAINT [PK_B_Id] PRIMARY KEY,
[Type] INT NOT NULL
)
GO
So, it is very simple scheme, but I want to add condition for foreign keys like "type should be 0". It should be something like
CONSTRAINT [FK_A_B] REFERENCES [B](Id) WHERE [B].[Type] = 0
How to use UNIQUE keyword or smth else correctly to realize it?
What you are trying to achieve is not a task for FOREIGN KEY. In FK you can't specify additional conditions on a target table. If you have such need, usually it means that your DB is not normalized. It looks like table [B] stores several data entities in one table, and Type column determines what entity it is. If you broke normalization rules, declarative integrity means like FK don't work for you. From now on you have to control integrity on your own. You can do this in application logic or create triggers (procedural integrity). In any case there will be no foreign key constraint in DB.
It would be nice if this could be done using a filtered unique index. But, SQL Server doesn't allow that. So here is another idea:
Start by defining a (redundant) unique constraint on:
CREATE TABLE [B] (
[Id] INT IDENTITY CONSTRAINT [PK_B_Id] PRIMARY KEY,
[Type] INT NOT NULL,
UNIQUE (ID, Type)
)
GO
Now, I don't think you can define the constraint as:
CONSTRAINT [FK_A_B] (ID, 0) REFERENCES [B](Id, Type)
But, I think you can trick it by doing:
_Type as 0,
CONSTRAINT [FK_A_B] (ID, _Type) REFERENCES [B](Id, Type)
That is, add a computed column and use that for the constraint.

In SQL does a Primary Key in a create table enforce uniqueness?

Im wondering if on a relational table I set the two values below as a PRIMARY KEY if that automatically makes the table know that all entries should be unique....
CREATE TABLE UserHasSecurity
(
userID int REFERENCES Users(userID) NOT NULL,
securityID int REFERENCES Security(securityID) NOT NULL,
PRIMARY KEY(userID,securityID)
)
or do I need to be more explicit like this...
CREATE TABLE UserHasSecurity
(
userID int REFERENCES Users(userID) NOT NULL,
securityID int REFERENCES Security(securityID) NOT NULL,
PRIMARY KEY(userID,securityID),
UNIQUE(userID,securityID)
)
You don't need UNIQUE here. PRIMARY KEY will make sure there is no duplicate (userID,securityID) pairs.
No, you don't need to specify UNIQUE in addition to PRIMARY KEY. A primary key by definition must be unique.
A PRIMARY KEY has to be unique, so you only need to declare as a primary key. The underlying index is unique by definition.
Creating Unique Indexes

Differences between "foreign key" and "constraint foreign key"

I mean for example I can create table like
create table XTable
(
idt int not null primary key,
value nvarchar(50),
idq int,
constraint fk_idq foreign key(idq) references YTable(idq)
)
and I can create it like this
create table XTable
(
idt int not null primary key,
value nvarchar(50),
idq int,
foreign key(idq) references YTable(idq)
)
I usually create table like in the second example but now I'm curious about the first example. What is the difference?
The first one assigns a user-defined name to the foreign key, the second one will assign a system-generated name to the foreign key.
User-defined foreign key names can be useful for subsequent statements like these:
ALTER TABLE XTable DROP CONSTRAINT fk_idq;
ALTER TABLE XTable ENABLE CONSTRAINT fk_idq;
ALTER TABLE XTable DISABLE CONSTRAINT fk_idq;
It's harder to alter constraints with system-generated names, as you have to discover those names first.
The first option is purely for naming the constraint.
From SQL FOREIGN KEY Constraint
To allow naming of a FOREIGN KEY constraint, and for defining a FOREIGN KEY constraint on multiple columns, use the following SQL syntax
CREATE TABLE Orders
(
O_Id int NOT NULL,
OrderNo int NOT NULL,
P_Id int,
PRIMARY KEY (O_Id),
CONSTRAINT fk_PerOrders FOREIGN KEY (P_Id)
REFERENCES Persons(P_Id)
)
Also, from CREATE TABLE (Transact-SQL) one can see that [ CONSTRAINT constraint_name ] is optional.
Apart from controlling the name, nothing really. SQL Server will supply a name if you omit it. FYI, you only need this syntax (SQL Fiddle):
create table XTable
(
idt int not null primary key,
value nvarchar(50),
idq int references YTable(idq)
)
Here's a fuller example.

How to add composite primary key to table

create table d(id numeric(1), code varchar(2))
After I create the above table how can I add a composite primary key on both fields and also a foreign key?
In Oracle, you could do this:
create table D (
ID numeric(1),
CODE varchar(2),
constraint PK_D primary key (ID, CODE)
);
alter table d add constraint pkc_Name primary key (id, code)
should do it. There's lots of options to a basic primary key/index depending on what DB your working with.
The ALTER TABLE statement presented by Chris should work, but first you need to declare the columns NOT NULL. All parts of a primary key need to be NOT NULL.
You don't need to create the table first and then add the keys in subsequent steps. You can add both primary key and foreign key while creating the table:
This example assumes the existence of a table (Codes) that we would want to reference with our foreign key.
CREATE TABLE d (
id [numeric](1),
code [varchar](2),
PRIMARY KEY (id, code),
CONSTRAINT fk_d_codes FOREIGN KEY (code) REFERENCES Codes (code)
)
If you don't have a table that we can reference, add one like this so that the example will work:
CREATE TABLE Codes (
Code [varchar](2) PRIMARY KEY
)
NOTE: you must have a table to reference before creating the foreign key.
If using Sql Server Management Studio Designer just select both rows (Shift+Click) and Set Primary Key.

could unique key ( not primary ) be a parent for declarative foreign key constraint

Naive question with the answer "No" , I believe, but still would like to ask.
Table_parent
pk_parent_surrogate
parent_natural_unique_key
Table_child
pk_child_surrogate
child_natural_NOT_unique
Is that true that the only possible declarative relationship among main database vendors is
pk_parent_surrogate ----------< pk_child_surrogate
and we can't have declarative constraint or foreign key in other words for pair
parent_natural_unique_key -------< child_natural_NOT_unique
My answer here is based on my MS SQL knowledge - although I believe the same answer is correct for ANSI standards as well, i'm not 100% sure...
YES - you CAN do this as long as you've got a unique constraint on the column in your parent table that you want to use as the anchor column for the key.
You can create a FOREIGN KEY constraint as part
of the table definition when you create a table.
If a table already exists, you can add a
FOREIGN KEY constraint, provided that the
FOREIGN KEY constraint is linked to an existing
PRIMARY KEY constraints or UNIQUE constraint in
another, or the same, table. A table can contain
multiple FOREIGN KEY constraints.
And as an example of this sort of key...
use tempdb
CREATE TABLE parent(
pk int identity primary key,
candidate_key int unique not null)
CREATE TABLE child(
pk int identity primary key,
join_key int references parent(candidate_key))
See here for more information.
Try code like this:
create table testunique (id int identity(1,1) primary key, otherid int)
go
create unique index ixOther on testunique(otherid)
go
create table testFK (id int identity(1,1) primary key, someid int)
go
alter table testFK add constraint fkTest foreign key (someid) references testunique(otherid)
Rob