CONSTRAINT causes error, but despite this, auto_increment is incremented - postgresql

I create table so:
CREATE TABLE mytable(
name CHARACTER VARYING CONSTRAINT exact_11char CHECK( CHAR_LENGTH(name) = 11 ) ,
age INTEGER
)
Then add id PRIMARY KEY column
ALTER TABLE mytable ADD COLUMN id BIGSERIAL PRIMARY KEY
Then, when trying insert in column name data, which character length isn't 11, happened error from CONSTRAINT.
Ok, but also, id column sequence is incremenmted on each failed attempts.
How to make so: on failed (reason CONSTRAINT) attempts, not increment auto_inceremented column?
postgreSQL version is: 9.2

Since the sequence operations are non-transactional. So there is no simple way exists in PostgreSQL to stop the increment operation on sequence when the corresponding insert fails.
Check the link to create a gapless sequences.
Gapless Sequences for Primary Keys

Related

INSERT INTO excluding ID column violates primary key uniqueness constraint

I have a Postgres 10.6 table with a serial ID column.
When I attempt to insert into it:
INSERT INTO table (col1, col2) VALUES ('foo', 'bar');
excluding the ID column from the column list, I get:
ERROR: duplicate key value violates unique constraint "customer_invoice_pkey"
Detail: Key (id)=(1234) already exists.
Subsequent runs of the query increment the ID in the error message (1235, 1236 etc.)
How can this be happening?
Having a serial column does not prevent you from inserting rows with an explicit value for id. The sequence value is only a default value that is used when id is not specified in the INSERT statement.
So there must have been some “rogue” inserts of that kind. From PostgreSQL v11 on, you can use identity columns (GENERATED ALWAYS AS IDENTITY) to make overriding the sequence value harder.
You could use the setval function to set the sequence to a value higher than the maximum id in the table to work around the problem.

postgresql make existing primary key auto incrementing when inserting

Existing table with 5 columns.
qid which is the PK, question geo_type user_input active
I need to be able to insert into the table with each new insert getting a new primary key id (which would be the max existing id +1).
So i need to be able to do this
insert into sip_questions (question,geo_type,user_input,active) values('noury','octagon',TRUE,TRUE)
but this give me this error
ERROR: duplicate key value violates unique constraint "s_questions_pkey"
DETAIL: Key (qid)=(1) already exists.
********** Error **********
ERROR: duplicate key value violates unique constraint "s_questions_pkey"
SQL state: 23505
Detail: Key (qid)=(1) already exists.
this is the table
CREATE TABLE public.sip_questions
(
qid integer NOT NULL DEFAULT nextval('s_questions_qid_seq'::regclass),
question character varying(200),
geo_type character varying(10),
user_input boolean,
active boolean,
CONSTRAINT s_questions_pkey PRIMARY KEY (qid)
)
WITH (
OIDS=FALSE
);
ALTER TABLE public.sip_questions
OWNER TO postgres;
i know how to do this from a fresh table like this
ALTER TABLE table ADD COLUMN id SERIAL PRIMARY KEY;
and every insert will increment the PK without me having to specify the id column
The new sequence must be bumped to the current max value.
You can reset it using
SELECT setval('s_questions_qid_seq', max(id)) FROM sip_questions;

How can I create a sequence in PostgreSQL to add nextval to an id column where the table already exists? [duplicate]

In a Postgres 9.3 table I have an integer as primary key with automatic sequence to increment, but I have reached the maximum for integer. How to convert it from integer to serial?
I tried:
ALTER TABLE my_table ALTER COLUMN id SET DATA TYPE bigint;
But the same does not work with the data type serial instead of bigint. Seems like I cannot convert to serial?
serial is a pseudo data type, not an actual data type. It's an integer underneath with some additional DDL commands executed automatically:
Create a SEQUENCE (with matching name by default).
Set the column NOT NULL and the default to draw from that sequence.
Make the column "own" the sequence.
Details:
Safely rename tables using serial primary key columns
A bigserial is the same, built around a bigint column. You want bigint, but you already achieved that. To transform an existing serial column into a bigserial (or smallserial), all you need to do is ALTER the data type of the column. Sequences are generally based on bigint, so the same sequence can be used for any integer type.
To "change" a bigint into a bigserial or an integer into a serial, you just have to do the rest by hand:
Creating a PostgreSQL sequence to a field (which is not the ID of the record)
The actual data type is still integer / bigint. Some clients like pgAdmin will display the data type serial in the reverse engineered CREATE TABLE script, if all criteria for a serial are met.

How to AUTO_INCREMENT in db2?

I thought this would be simple, but I can't seem to use AUTO_INCREMENT in my db2 database. I did some searching and people seem to be using "Generated by Default", but this doesn't work for me.
If it helps, here's the table I want to create with the sid being auto incremented.
create table student(
sid integer NOT NULL <auto increment?>
sname varchar(30),
PRIMARY KEY (sid)
);
Any pointers are appreciated.
You're looking for is called an IDENTITY column:
create table student (
sid integer not null GENERATED ALWAYS AS IDENTITY (START WITH 1 INCREMENT BY 1)
,sname varchar(30)
,PRIMARY KEY (sid)
);
A sequence is another option for doing this, but you need to determine which one is proper for your particular situation. Read this for more information comparing sequences to identity columns.
You will have to create an auto-increment field with the sequence object (this object generates a number sequence).
Use the following CREATE SEQUENCE syntax:
CREATE SEQUENCE seq_person
MINVALUE 1
START WITH 1
INCREMENT BY 1
CACHE 10
The code above creates a sequence object called seq_person, that starts with 1 and will increment by 1. It will also cache up to 10 values for performance. The cache option specifies how many sequence values will be stored in memory for faster access.
To insert a new record into the "Persons" table, we will have to use the nextval function (this function retrieves the next value from seq_person sequence):
INSERT INTO Persons (P_Id,FirstName,LastName)
VALUES (seq_person.nextval,'Lars','Monsen')
The SQL statement above would insert a new record into the "Persons" table. The "P_Id" column would be assigned the next number from the seq_person sequence. The "FirstName" column would be set to "Lars" and the "LastName" column would be set to "Monsen".
hi If you are still not able to make column as AUTO_INCREMENT while creating table. As a work around first create table that is:
create table student(
sid integer NOT NULL
sname varchar(30),
PRIMARY KEY (sid)
);
and then explicitly try to alter column bu using the following
alter table student alter column sid set GENERATED BY DEFAULT AS
IDENTITY
Or
alter table student alter column sid set GENERATED BY DEFAULT
AS IDENTITY (start with 100)
Added a few optional parameters for creating "future safe" sequences.
CREATE SEQUENCE <NAME>
START WITH 1
INCREMENT BY 1
NO MAXVALUE
NO CYCLE
CACHE 10;

How can I add a 2nd serial integer key column to a table? (postgresql)

I have a table with 8440 records with a natural (string) primary key. Now I just discovered that to support a legacy client, I need the records to have integer keys as well. what's the easiest way to add a serial INT column to this table with a unique constraint and populate it with integer values from 1 to 8440?
Alter the table, add a new not null column of type serial, with a unique key on it.
In Postgres, the serial type is a mere alias for the int type with a default value of nextval(some_sequence), the latter of which is created on the fly.