Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Foreign keys and NULL in mySQL

Tags:

Can I have a column in my values table (value) referenced as a foreign key to knownValues table, and let it be NULL whenever needed, like in the example:

Table: values

 product     type     value     freevalue  0           1        NULL      100  1           2        NULL      25  3           3        1         NULL 

Table: types

 id    name     prefix  0     length   cm  1     weight   kg  2     fruit    NULL 

Table: knownValues

id    Type     name 0     2        banana  

Note: The types in the table values & knownValues are of course referenced into the types table.

like image 282
Industrial Avatar asked May 10 '10 12:05

Industrial


People also ask

Can a foreign key have nulls?

A foreign key containing null values cannot match the values of a parent key, since a parent key by definition can have no null values. However, a null foreign key value is always valid, regardless of the value of any of its non-null parts.

Why my foreign key is null?

Q: Why foreign key is null? A: Whether or not a column can contain a NULL value is determined by the presence or absence of a NOT NULL constraint. This is entirely independent of whether the column is referenced in a foreign key constraint.

Can we insert null in a foreign key column?

Yes. If a column is marked as nullable while creating the table, you can insert null in column which is a foreign key. Yes,You can null value in Foreign key Column.


2 Answers

NULLs in foreign keys are perfectly acceptable. Dealing with NULLs in foreign keys is tricky but that does not mean that you change such columns to NOT NULL and insert dummy ("N/A", "Unknown", "No Value" etc) records in your reference tables.

Using NULLs in foreign keys often requires you to use LEFT/RIGHT JOIN instead of INNER JOIN.

like image 62
Salman A Avatar answered Sep 21 '22 03:09

Salman A


Although you can make foreign key columns nullable I would suggest that it's generally better to design tables without nullable foreign keys. Nulls invariably lead to certain ambiguities and incorrect results but that's doubly a problem if the columns in question are expected to be subject to some constraint.

like image 38
nvogel Avatar answered Sep 24 '22 03:09

nvogel