Indexing Foreign keys - sql

How do I index a foreign key in Oracle?

CREATE TABLE reftable (id INT NOT NULL PRIMARY KEY)
CREATE TABLE mytable (id INT NOT NULL, ref INT NOT NULL)
ALTER TABLE mytable
ADD CONSTRAINT fk_mytable_ref_reftable
FOREIGN KEY (ref) REFERENCES reftable (id)
CREATE INDEX ix_mytable_ref ON mytable (ref)
The column in another table (the one you are referencing) must be a PRIMARY KEY or have a UNIQUE constraint defined on it, which means it already has an index.

You cannot index the foreign key constraint itself, but you can index the columns the foreign key is defined on.
Regards,
Rob.

Related

SQL: Having a primary key also be a foreign key

For this question, I am referring to the specific case where you have table T, it has primary key K, but K is a foreign key. Is this valid? And how would you write it in SQL99?
All the other questions I've seen on here are just asking whether or not a primary key can be a foreign key for another table. That's not what I'm asking about. I'm asking about a table which has a foreign key where that is the primary key of that table.
If I understand you correctly, you want to create a hierarchical table, for instance:
create table hierarchical
(
id number primary key,
parent_id number
);
alter table hierarchical add constraint
fk_parent_id foreign key(parent_id) references hierarchical(id);
This kind of table can contain employees/managers for instance.
A column can be a primary key as well foreign key. For example, refer to the following:
A column can be both a primary key and a foreign key. For example:
create table A
(
id int not null
, constraint PK_A primary key (id)
);
create table B
(
id int not null
,constraint PK_B primary key (id)
,constraint FK_B_ID foreign key (id) references A(id)
);
Though, this requires data to be present in Table B first.

There are no PK in the referenced table. Why?

I have the following T-SQL to create 3 SQL tables:
create table dbo.Posts
(
Id int identity not null
constraint PK_Posts_Id primary key clustered (Id),
Active bit not null
constraint DF_Posts_Active default (0)
);
create table dbo.PostsLocalized
(
Id int not null,
Culture int not null
constraint CK_PostsLocalized_Culture check ([Culture] in ('1', '2', '3')),
[Text] nvarchar (200) not null,
constraint PK_PostsLocalized_Id_Culture primary key clustered (Id, Culture)
);
create table dbo.Tags
(
Id int identity not null
constraint PK_Tags_Id primary key clustered (Id),
Name nvarchar not null
);
create table dbo.PostsLocalized_Tags
(
PostLocalizedId int not null,
TagId int not null,
constraint PK_PostsLocalized_Tags_Post_PostLocalizedId_TagId primary key clustered (PostLocalizedId, TagId)
);
Then I have added the following constraints:
alter table dbo.PostsLocalized
add constraint FK_PostsLocalized_Id foreign key (Id) references dbo.Posts(Id) on delete cascade on update cascade;
alter table dbo.PostsLocalized_Tags
add constraint FK_PostsLocalized_Tags_PostLocalizedId foreign key (PostLocalizedId) references PostsLocalized(Id) on delete cascade on update cascade,
constraint FK_PostsLocalized_Tags_TagId foreign key (TagId) references Tags(Id) on delete cascade on update cascade;
But I get the following error:
There are no primary or candidate keys in the referenced table 'PostsLocalized' that match the referencing column list in the foreign key 'FK_PostsLocalized_Tags_PostLocalizedId'.
How can I solve this?
Thank You,
Miguel
SQL Server mandates that foreign key references be to a primary key or unique key. The foreign key reference has to be to all the columns that constitute the primary/unique key. The documentation says:
In a foreign key reference, a link is created between two tables when
the column or columns that hold the primary key value for one table
are referenced by the column or columns in another table. This column
becomes a foreign key in the second table.
A FOREIGN KEY constraint does not have to be linked only to a PRIMARY
KEY constraint in another table; it can also be defined to reference
the columns of a UNIQUE constraint in another table. A FOREIGN KEY
constraint can contain null values; however, if any column of a
composite FOREIGN KEY constraint contains null values, verification of
all values that make up the FOREIGN KEY constraint is skipped. To make
sure that all values of a composite FOREIGN KEY constraint are
verified, specify NOT NULL on all the participating columns.
The primary key in PostsLocalized contains the culture column, so you need to add it into the foreign key reference.
Your PK on PostsLocalized table is complex consisting of two columns - id and culture and you are trying to create FK on only one of those columns which is not possible.
You'll have to either add Culture column on PostsLocalized_Tags and use them both in foreign key or remove Culture from your PK on PostLocalized

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 create composite primary key in SQL Server 2008

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

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