1

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?

jarlh
  • 42,561
  • 8
  • 45
  • 63
lei
  • 13
  • 4
  • Does this answer your question? [Postgresql: How to use ENUM datatype?](https://stackoverflow.com/questions/38474575/postgresql-how-to-use-enum-datatype) – Azhar Khan Oct 20 '22 at 04:35
  • 1
    Note that tables have _columns_, not fields. – jarlh Oct 20 '22 at 06:13

2 Answers2

1

Try Below

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

CREATE TABLE t (
    g gender default 'F' -- <==== default value
);
Rahul Beniwal
  • 639
  • 4
  • 9
0

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.

Laurenz Albe
  • 209,280
  • 17
  • 206
  • 263