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
2009-08-15 11:29:33
I already have a sequence, and curval is 3,but I want to product even numbers 4,6,8,10...
yjfuk
2009-08-15 16:46:41
+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
2009-08-15 13:05:15