Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You can use a lookup table with a VARCHAR primary key, and your main data table uses a FOREIGN KEY on its column, with cascading updates.</p> <pre><code>CREATE TABLE ColorLookup ( color VARCHAR(20) PRIMARY KEY ); CREATE TABLE ItemsWithColors ( ...other columns..., color VARCHAR(20), FOREIGN KEY (color) REFERENCES ColorLookup(color) ON UPDATE CASCADE ON DELETE SET NULL ); </code></pre> <p>This solution has the following advantages:</p> <ul> <li>You can query the color names in the main data table without requiring a join to the lookup table.</li> <li>Nevertheless, color names are constrained to the set of colors in the lookup table.</li> <li>You can get a list of unique colors names (even if none are currently in use in the main data) by querying the lookup table.</li> <li>If you change a color in the lookup table, the change automatically cascades to all referencing rows in the main data table.</li> </ul> <hr> <p>It's surprising to me that so many other people on this thread seem to have mistaken ideas of what "normalization" is. Using a surrogate keys (the ubiquitous "id") has nothing to do with normalization!</p> <hr> <p>Re comment from @MacGruber:</p> <p>Yes, the size is a factor. In InnoDB for example, every secondary index stores the primary key value of the row(s) where a given index value occurs. So the more secondary indexes you have, the greater the overhead for using a "bulky" data type for the primary key. </p> <p>Also this affects foreign keys; the foreign key column must be the same data type as the primary key it references. You might have a small lookup table so you think the primary key size in a 50-row table doesn't matter. But that lookup table might be referenced by millions or <em>billions</em> of rows in other tables!</p> <p>There's no right answer for all cases. Any answer can be correct for different cases. You just learn about the tradeoffs, and try to make an informed decision on a case by case basis.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload