Skip to content

Latest commit

 

History

History
39 lines (31 loc) · 1.09 KB

enums.md

File metadata and controls

39 lines (31 loc) · 1.09 KB

Creating references

Sometimes we want to limit the selection of data for certain fields. A basic example is gender, where it can have only 'M' or 'F'. But what if the data is something that changes over time, say category or subcategory of an item, or country/currency list?

There are few ways to enforce the constraint:

  • enum
  • set
  • check constraint
  • lookup table

Example with Check Constraint

CREATE TABLE user (
  name varchar(255),
  gender char,
  CONSTRAINT valid gender
     CHECK (gender IN 'M', 'F')
)

Example with Lookup Table

CREATE TABLE user (
  name varchar(255),
  gender char,
  FOREIGN KEY (gender) REFERENCES gender(type)
)

CREATE TABLE gender(
  type char PRIMARY KEY
)

A typical mistake is to create a reference table with an auto-increment primary key, and linking that id to the table. It makes querying more troublesome, as one as to select the type back from the reference table.

References: