Question

How to create table with pre-specified values for a column.

Something like enum, but not an enum, because it works from 8.3 Postgres and I need something working with 8.1 and later versions.

for example

CREATE TABLE (
    cars ('bmw', 'audi');
)

And I shouldn't be able to insert anything else except bmw and audi when inserting a value to the cars column.

Was it helpful?

Solution

I think what you are looking for is the CHECK constraint.

create table mydata(
cars char(4)CONSTRAINT limit_cars_to CHECK (cars in ('bmw', 'audi'))
);

insert into mydata values('bmw'); /*this insert works*/
insert into mydata values('xxx');/*this insert fails msg: ERROR: new row for relation "mydata" violates check constraint "limit_cars_to": insert into mydata values('xxx')
*/

I have tested this with PostgreSQL 8.3 ( as that is what is availabel on SQL Fiddle). Might just work with PostgreSQL 8.1. Give it a try.

Source: http://www.postgresql.org/docs/8.1/static/ddl-constraints.html

OTHER TIPS

There are two ways to solve this problem.

The first is to use a check constraint, and Sashikanth's answer describes it. This approach should be used if the allowable values don't change. If they do change, you need to update the constraint which in many organisations can require a long process to get into production.

The second is to use a foreign key to another table listing the allowable values:

create table cars (
    car varchar(10) primary key
);

create table mydata (
   id serial primary key,
   car varchar(10) references cars
);

This approach should be used if you expect the values to change, or if the users need to be able to add values.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top