views:

171

answers:

2

I want set some constraint to the serial type,it only produce even or odd numbers.

+2  A: 

SERIAL is a syntax sugar around creating and using sequences.

So you could do it all manually and create a special type of sequence that suits your needs:

CREATE SEQUENCE tablename_colname_seq INCREMENT BY 2 START WITH 2;

CREATE TABLE tablename (
    colname integer NOT NULL DEFAULT nextval('tablename_colname_seq');

ALTER SEQUENCE tablename_colname_seq OWNED BY tablename.colname;

Or if you already have a table and a SERIAL column you could change the underlying sequence:

ALTER SEQUENCE tablename_colname_seq INCREMENT BY 2;

The name of the underlying sequence could be retrieved by "describing" the table using psql:

\d tablename
Milen A. Radev
I already have a sequence, and curval is 3,but I want to product even numbers 4,6,8,10...
yjfuk
+1  A: 

Simply, set your serial to increment by 2, and to start on either 1 or 2 for producing either odd or even number:

Odd

CREATE SEQUENCE odd_seq INCREMENT BY 2 START WITH 1;

Even

CREATE SEQUENCE even_seq INCREMENT BY 2 START WITH 2;
nos
could I change the default create sequence increment by 2?
yjfuk