Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgres Sequence is generating negative values as primary keys

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)

questionnaries.sql #

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;

questionnaries_id_seq

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;
like image 303
samdset Avatar asked May 28 '26 19:05

samdset


2 Answers

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,

  1. 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;
    
  2. 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');
like image 27
Ankur Srivastava Avatar answered May 31 '26 11:05

Ankur Srivastava