Skip to content
Advertisement

How to allow a gender field to accept only two values?

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?

Advertisement

Answer

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.

6 People found this is helpful
Advertisement