Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of null values in related tables with foreign key constraints

I have the following tables:

Cateogories

  • CategoryID (int) Primary Key
  • CategoryName (varchar)

Items

  • ItemID (int) Primary Key
  • CategoryID (int)
  • ItemName (varchar)

There is a foreign key constraint on Items.CategoryID. There is a chance that when a new item is created that there will be no category assigned.

Is it better to set Items.CategoryID to allow nulls and deal with the nulls in my code OR better to not allow nulls, set the default CategoryID to 1, and create a dummy record in the Categories table called "Uncategorized" and then deal with that dummy category in my code?

like image 749
jpshook Avatar asked Jan 07 '10 13:01

jpshook


People also ask

Does foreign key constraint allow null values?

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.

Why foreign keys are allowed to have null values?

Yes, foreign keys are allowed to have NULL values, Foreign keys simply require that the value in that field must exist first in a different table (the parent table). However, Null by definition is not a value. Null signifies that we do not yet know what the value is.

Why do we use NULL value in a table?

A field with a NULL value is a field with no value. If a field in a table is optional, it is possible to insert a new record or update a record without adding a value to this field. Then, the field will be saved with a NULL value. Note: A NULL value is different from a zero value or a field that contains spaces.


1 Answers

The logically correct way would be for the CategoryID column to be NULL when there is no Category for the item.

If you get trapped by any of the gotchas that are associated with using NULL, then that is most likely a sign that the design hasnt taken account of the fact that items cannot have a category. Fix the design. The NULL will ensure you stick to solving the correct problem.

like image 144
Mongus Pong Avatar answered Nov 14 '22 22:11

Mongus Pong