Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a foreign key reference a non-unique index?

I thought a foreign key meant that a single row must reference a single row, but I'm looking at some tables where this is definitely not the case. Table1 has column1 with a foreign key constraint on column2 in table2, BUT there are many records in table2 with the same value in column2. There's also non-unique index on column2. What does this mean? Does a foreign key constraint simply mean that at least one record must exist with the right values in the right columns? I thought it meant there must be exactly one such record (not sure how nulls fit in to the picture, but I'm less concerned about that at the moment).

update: Apparently, this behavior is specific to MySQL, which is what I was using, but I didn't mention it in my original question.

like image 996
allyourcode Avatar asked Feb 26 '09 01:02

allyourcode


People also ask

Can a foreign key reference a non unique column?

InnoDB allows a foreign key constraint to reference a non-unique key. This is an InnoDB extension to standard SQL. However, there is a pratical reason to avoid foreign keys on non-unique columns of referenced table.

Does a foreign key have to be unique can it be null?

Foreign keys allow key values that are all NULL , even if there are no matching PRIMARY or UNIQUE keys. By default (without any NOT NULL or CHECK clauses), the FOREIGN KEY constraint enforces the match none rule for composite foreign keys in the ANSI/ISO standard.

Can a foreign key reference a UNIQUE constraint?

A UNIQUE constraint can be referenced by a FOREIGN KEY constraint. When a UNIQUE constraint is added to an existing column or columns in the table, by default, the Database Engine examines the existing data in the columns to make sure all values are unique.

Is foreign key unique or index?

Foreign keys do not create indexes. Only alternate key constraints(UNIQUE) and primary key constraints create indexes.


2 Answers

From MySQL documentation:

InnoDB allows a foreign key constraint to reference a non-unique key. This is an InnoDB extension to standard SQL.

However, there is a pratical reason to avoid foreign keys on non-unique columns of referenced table. That is, what should be the semantic of "ON DELETE CASCADE" in that case?

The documentation further advises:

The handling of foreign key references to nonunique keys or keys that contain NULL values is not well defined (...) You are advised to use foreign keys that reference only UNIQUE (including PRIMARY) and NOT NULL keys.

like image 153
Hobbes Avatar answered Oct 12 '22 19:10

Hobbes


Your analysis is correct; the keys don't have to be unique, and constraints will act on the set of matching rows. Not usually a useful behavior, but situations can come up where it's what you want.

like image 38
chaos Avatar answered Oct 12 '22 18:10

chaos