postgresql make existing primary key auto incrementing when inserting - postgresql

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;

Related

ERROR: there is no unique constraint matching given keys for referenced table "mail_message" Odoo Postgres [duplicate]

Trying to create this example table structure in Postgres 9.1:
CREATE TABLE foo (
name VARCHAR(256) PRIMARY KEY
);
CREATE TABLE bar (
pkey SERIAL PRIMARY KEY,
foo_fk VARCHAR(256) NOT NULL REFERENCES foo(name),
name VARCHAR(256) NOT NULL,
UNIQUE (foo_fk,name)
);
CREATE TABLE baz(
pkey SERIAL PRIMARY KEY,
bar_fk VARCHAR(256) NOT NULL REFERENCES bar(name),
name VARCHAR(256)
);
Running the above code produces an error, which does not make sense to me:
NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "foo_pkey" for table "foo"
NOTICE: CREATE TABLE will create implicit sequence "bar_pkey_seq" for serial column "bar.pkey"
NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "bar_pkey" for table "bar"
NOTICE: CREATE TABLE / UNIQUE will create implicit index "bar_foo_fk_name_key" for table "bar"
NOTICE: CREATE TABLE will create implicit sequence "baz_pkey_seq" for serial column "baz.pkey"
NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "baz_pkey" for table "baz"
ERROR: there is no unique constraint matching given keys for referenced table "bar"
********** Error **********
ERROR: there is no unique constraint matching given keys for referenced table "bar"
SQL state: 42830
Can anyone explain why this error arises?
It's because the name column on the bar table does not have the UNIQUE constraint.
So imagine you have 2 rows on the bar table that contain the name 'ams' and you insert a row on baz with 'ams' on bar_fk, which row on bar would it be referring since there are two rows matching?
In postgresql all foreign keys must reference a unique key in the parent table, so in your bar table you must have a unique (name) index.
See also http://www.postgresql.org/docs/9.1/static/ddl-constraints.html#DDL-CONSTRAINTS-FK and specifically:
Finally, we should mention that a foreign key must reference columns
that either are a primary key or form a unique constraint.
Emphasis mine.
You should have name column as a unique constraint. here is a 3 lines of code to change your issues
First find out the primary key constraints by typing this code
\d table_name
you are shown like this at bottom "some_constraint" PRIMARY KEY, btree (column)
Drop the constraint:
ALTER TABLE table_name DROP CONSTRAINT some_constraint
Add a new primary key column with existing one:
ALTER TABLE table_name ADD CONSTRAINT some_constraint PRIMARY KEY(COLUMN_NAME1,COLUMN_NAME2);
That's All.
when you do UNIQUE as a table level constraint as you have done then what your defining is a bit like a composite primary key see ddl constraints, here is an extract
This specifies that the combination of values in the indicated columns is unique across the whole table, though any one of the columns need not be (and ordinarily isn't) unique.
this means that either field could possibly have a non unique value provided the combination is unique and this does not match your foreign key constraint.
most likely you want the constraint to be at column level. so rather then define them as table level constraints, 'append' UNIQUE to the end of the column definition like name VARCHAR(60) NOT NULL UNIQUE or specify indivdual table level constraints for each field.

postgres doesn't drop not null

I drop not null on primary key column, and it executes, after I check schema of table and there is not null
table:
-- auto-generated definition
create table warehouses
(
id_warehouse serial not null
constraint warehouse_pkey
primary key,
responsible_person varchar(30) not null
);
script to drop not null:
alter table warehouses
drop constraint warehouse_pkey;
alter table warehouses
alter id_warehouse drop not null;
alter table warehouses
add constraint warehouse_pkey
primary key (id_warehouse);
Per information here:
https://www.postgresql.org/docs/current/sql-createtable.html
PRIMARY KEY (column constraint)
The PRIMARY KEY constraint specifies that a column or columns of a table can contain only unique (non-duplicate), nonnull values. Only one primary key can be specified for a table, whether as a column constraint or a table constraint.
A column defined as PRIMARY KEY will also have the NOT NULL constraint set.

PostgreSQL v10 got an error when using insert .. on conflict .. update on partitioned table

I have the following table in my database, the table was created using django and architect.
CREATE TABLE public.results
(
results_id integer NOT NULL DEFAULT nextval('results_results_id_seq'::regclass),
name character varying(45) COLLATE pg_catalog."default" NOT NULL,
value double precision NOT NULL,
scenario_id integer NOT NULL,
CONSTRAINT results_pkey PRIMARY KEY (results_id),
CONSTRAINT results_scenario_id_name_22ad9c45_uniq UNIQUE (scenario_id, name),
CONSTRAINT results_scenario_id_d800e53c_fk_scenario_scenario_id FOREIGN KEY (scenario_id)
REFERENCES public.scenario (scenario_id) MATCH SIMPLE
ON UPDATE NO ACTION
ON DELETE NO ACTION
DEFERRABLE INITIALLY DEFERRED
)
WITH (
OIDS = FALSE
)
TABLESPACE pg_default;
The problem I face occurs when I run the following query
insert into
results ("scenario_id","name","value")
values
(44,'footprint_km2',1000)
on conflict
("scenario_id","name")
do update set
"value"= excluded.value;
duplicate key value violates unique constraint "results_1_500000_scenario_id_name_key"
DETAIL: Key (scenario_id, name)=(44, footprint_km2) already exists
which makes no sense to me because I specified an update action when a conflict occurs.
¿Do you know what I am doing wrong?

CONSTRAINT causes error, but despite this, auto_increment is incremented

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

PostgreSQL: after import some data, if insert there is error - IntegrityError duplicate key value violates unique constraint "place_country_pkey"

When I import some data to PostgreSQL through PhpPgAdmin there is all fine.
But when I try later to insert some data to populated before tables I get an error:
IntegrityError: duplicate key value violates unique constraint "place_country_pkey"
And this is happens only with prepopulated tables.
Here is my SQL:
DROP TABLE IF EXISTS place_country CASCADE;
CREATE TABLE place_country (
id SERIAL PRIMARY KEY,
country_en VARCHAR(100) NOT NULL,
country_ru VARCHAR(100) NOT NULL,
country_ua VARCHAR(100) NOT NULL
);
INSERT INTO place_country VALUES(1,'Ukraine','Украина','Україна');
How to avoid this?
Thanks!
Try not inserting the "1". IIRC, in Postgres, when you define a column as SERIAL, it means that it will auto-generate an ID with a counter to automatically populate that column. So use:
INSERT INTO place_country (country_en, country_ru, country_ua) VALUES (Ukraine','Украина','Україна');
Which is a good practice anyway, BTW (explicitly naming the columns in an INSERT, I mean).