Home > Enterprise >  How to allow a gender field to accept only two values?
How to allow a gender field to accept only two values?

Time:10-20

The question: Add a gender field. Ensure the field will only accept ‘M’ or ‘F’ and the default value should be ‘F’

PostgresSQL code:

alter table Patient
add Gender varchar(1)  default 'F' ,Check (Gender = 'M' or Gender = 'F');

ERROR: syntax error at or near "Check"
LINE 2: add Gender varchar(1) default 'F' ,Check (Gender = 'M' or G...

How do i fix it?

CodePudding user response:

Try Below

CREATE TYPE gender AS ENUM ('F', 'M');

CREATE TABLE t (
    g gender default 'F' -- <==== default value
);

CodePudding user response:

Your approach is good, there is only a small syntax error:

alter table Patient
   add Gender varchar(1) default 'F',
   add Check (Gender = 'M' or Gender = 'F');

The second add was missing. Using IN would be typographically shorter.

  • Related