I have a table which uses a sequence to auto-generate the Primary Key when inserting a record. However, the sequence is generating negative values.
How do I enforce that only positive values are generated and is there a way to generated the ids randomly (especially a varchar type)
CREATE TABLE public.questionnaries
(
id integer NOT NULL DEFAULT nextval('questionnaries_id_seq'::regclass),
personname character varying(255) NOT NULL,
question character varying(255) NOT NULL,
response character varying(255) NOT NULL,
CONSTRAINT questionnaries_pkey PRIMARY KEY (id)
)
WITH (
OIDS=FALSE
);
ALTER TABLE public.questionnaries
OWNER TO postgres;
CREATE SEQUENCE public.questionnaries_id_seq
INCREMENT 1
MINVALUE 1
MAXVALUE 9223372036854775807
START 6
CACHE 1;
ALTER TABLE public.questionnaries_id_seq
OWNER TO postgres;
The Sequence generate the negative value in two scenarios,
1# you have created the sequence and specify the INCREMENT BY values in a negative("-1").
2# The sequence INCREMENT BY is in positive and correct form but, sequence reached to their MAX value and that's the reason it started generating the MIN value of the sequence.
There will two solutions for this,
Use the "NO MAXVALUE" with "NO CYCLE" parameter of the sequence as specified below.
CREATE SEQUENCE <> NO MAXVALUE START WITH 0 INCREMENT BY 1 NO CYCLE;
Use the "SERIAL" to generate the numerical values by PostgreSQL.
CREATE TABLE table_name (
column_1 integer PRIMARY KEY DEFAULT nextval('serial'),
column_2 varchar(40) NOT NULL
);
First Create a Sequence like below .Whichever number you wanna start give that for e.g. 0 or 100.
CREATE SEQUENCE questionnaries_id_seq START 0;
you can query also
SELECT nextval('questionnaries_id_seq');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With