sqlsqlitesql-types

Specifying choices for SQL table data types - sqlite


I'm working on setting up a table where one of the requirements is that a column should be "gender" and the data it accepts should be either "M" or "F". How do I specify this condition?

CREATE TABLE bears (
  id INTEGER PRIMARY KEY,
  name TEXT,
  age INTEGER,
  gender ("M" or "F")
)

Solution

  • One simple method is a check constraint:

    create table t as (
        . . .,
        gender char(1) not null,
        constraint chk_t_gender check (gender in ('M', 'F'))
    );
    

    Note that SQLite ignores the (1) on the character type, but the check constraint enforces the length. Written in this way, the code follows standard SQL.