Specifying choices for SQL table data types - sqlite

642 Views Asked by At

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")
)
1

There are 1 best solutions below

0
Gordon Linoff On BEST ANSWER

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.