PostgreSQL & PHP Tutorials - PostgreSQL Enum Types
An enum datatype allows only certain values to be entered into a particular field (for example - 'red', 'blue', 'yellow', 'purple' for favourite colours).
Postgresql doesn't have an enum datatype, but we can emulate it quickly and easily.
Instead of an enum type we can set up a CHECK CONSTRAINT - this tells postgresql to make sure that the value we are entering is valid.
CREATE TABLE person (
personid int not null primary key,
favourite_colour varchar(255) NOT NULL,
CHECK (favourite_colour IN ('red', 'blue', 'yellow', 'purple'))
);
Now that's done, let's check it works:
test=# insert into person(personid, favourite_colour) values (1, 'red');
INSERT 0 1
Now for something not in the list:
test=# insert into person(personid, favourite_colour) values (2, 'green');
ERROR: new row for relation "person" violates check constraint "person_favourite_colour_check"
Done! Nice and easy!
Avg Rating: 4
Vote Count: 19
