Duplicate key during import in PostgreSQL - postgresql

I am following an PostgreSQL book, and had to import a CSV file into a table census.lu_tracts.
Problem: When performing the INSERT query as shown below, I get the error:
ERROR: duplicate key value violates unique constraint "pk_lu_tracts"
DETAIL: Key (tract_id)=(25001010800) already exists.
How did the key becomes duplicate? SELECT * from lu_tracs shows 0 rows.
CREATE SCHEMA census;
set search_path=census;
CREATE TABLE lu_tracts(tract_id varchar(11), tract_long_id varchar(25)
, tract_name varchar(150)
, CONSTRAINT pk_lu_tracts PRIMARY KEY (tract_id));
INSERT INTO lu_tracts( tract_id, tract_long_id, tract_name)
SELECT geo_id2, geo_id, geo_display
FROM staging.factfinder_import
WHERE geo_id2 ~ '^[0-9]+';

The right answer is DISTINCT ON (geo_id2) which will select only one row per geo_id2 (more in the manual), it should be accompanied by an ORDER BY clause that will specify what row will be choosen.

Related

postgres key is not present in table constraint

When trying to ALTER TABLE in Postgres 9.5 to create foreign key constraint: from product_template.product_brand_id to product_brand.id
ALTER TABLE public.product_template
ADD CONSTRAINT product_template_product_brand_id_fkey
FOREIGN KEY (product_brand_id)
REFERENCES public.product_brand (id) MATCH SIMPLE
ON UPDATE NO ACTION
ON DELETE SET NULL;
Returns error
ERROR: insert or update on table "product_template" violates foreign key constraint "product_template_product_brand_id_fkey"
DETAIL: Key (product_brand_id)=(12) is not present in table "product_brand".
STATEMENT: ALTER TABLE "product_template" ADD FOREIGN KEY ("product_brand_id") REFERENCES "product_brand" ON DELETE set null
Im confused why postgres is trying to find product_brand.product_brand_id, when the fkey is from product_template.product_brand_id to product_brand.id
Any ideas?
The error message simply states that there is at least one row in the table product_template that contains the value 12 in the column product_brand_id
But there is no corresponding row in the table product_brand where the column id contains the value 12
Key (product_brand_id)=(12) relates the source column of the foreign key, not the target column.
In simple terms, the value of FOREIGN KEY(product_brand_id) provided in your ALTER statement is not present in the source (product_brand) table.

Postgres UPSERT syntax confusion

I have a table with 2 columns:
channels TEXT
rowid INTEGER PRIMARY KEY
I included an index on channels
CREATE UNIQUE INDEX channels_index on mytable (lower(channels))
so that VisitToronto will be a conflict with visittoronto
All works well and the conflict fires.
ERROR: duplicate key value violates unique constraint "channels_index"
DETAIL: Key (lower(words))=(hello world) already exists.
I can not figure out the syntax to trap this conflict. ON CONFLICT channels doesn't work ON CONFLICT ON CONSTRAINT channels_index doesn't work
The closest I've got is:
ERROR: there is no unique or exclusion constraint matching the ON CONFLICT specification
Any direction would be appreciated.
TIA
Use the index expression, i.e. lower(channels):
insert into my_table (channels) values
('VisitToronto');
insert into my_table (channels)
values ('visittoronto')
on conflict (lower(channels)) do
update set channels = excluded.channels;
select *
from my_table;
id | channels
----+--------------
1 | visittoronto
(1 row)
You are not able to use a constraint because the index is on an expression. In the case Postgres cannot create a constraint:
alter table my_table add constraint channels_unique unique using index channels_index;
ERROR: index "channels_index" contains expressions
LINE 1: alter table my_table add constraint channels_unique unique u...
^
DETAIL: Cannot create a primary key or unique constraint using such an index.

Insert into table after pg dump

I used pg_dump to populate a table in new database. After that, I want to be able to insert rows into table using the default autoincrementer of the serial key. Here is what I have in table:
In this table (smtable), a is the key (set as serial).
--data filled using pg dump
a | b
1 2
2 5
Now when I do the following statement:
INSERT INTO smtable VALUES(DEFAULT, 6)
RETURNING a INTO id;
I get the following error:
[error: duplicate key value violates unique constraint "a_pkey"]
detail: 'Key (a)=(1) already exists.
How do I get this statement to insert next_key of the table..
You might set the serial to the greatest number of your current id column to solve the issue. Since serial columns are associated with a sequence, just set it using this:
SELECT setval('smtable_a_seq', max(a)) FROM table;

How to reorg the indexes in DB2 database

I have to reorg all the index for table
I am getting the following error
SQL Error [23505]: One or more values in the INSERT statement, UPDATE statement, or foreign key update caused by a DELETE statement are not valid because the primary key, unique constraint or unique index identified by "2" constrains table "GMS4.SMS_PHYSICAL_CUSTOMER_DATA" from having duplicate values for the index key.. SQLCODE=-803, SQLSTATE=23505, DRIVER=4.16.53
One or more values in the INSERT statement, UPDATE statement, or foreign key update caused by a DELETE statement are not valid because the primary key, unique constraint or unique index identified by "2" constrains table "GMS4.SMS_PHYSICAL_CUSTOMER_DATA" from having duplicate values for the index key.. SQLCODE=-803, SQLSTATE=23505, DRIVER=4.16.53
DB2 Version 10
Please help..
I'm assuming you're on DB2 for Linux/Unix/Windows, here.
Your problem is not that you need to reorg your tables. The problem is that you are trying to insert a row, but you have a unique index on that table, which is preventing the insert.
You can see the name of the index, and the columns it is unique for by using this query:
SELECT
I.INDSCHEMA
,I.INDNAME
,C.COLNAME
FROM SYSCAT.INDEXES I
JOIN SYSCAT.INDEXCOLUSE C
ON I.INDSCHEMA = C.INDSCHEMA
AND I.INDNAME = C.INDNAME
WHERE I.IID = #indexID
AND I.TABSCHEMA = #tableSchema
AND I.TABNAME = #tableName
ORDER BY C.COLSEQ
;
You can get all of the parameters needed for this query from your error message. In this case, #indexId would be 2, #tableSchema would be GMS4, and #tableName would be SMS_PHYSICAL_CUSTOMER_DATA.

Postgresql User Defined Type in primary key constraint

I'm using postgresql 9.1 on Ubuntu 12.04. I have a user defined type as one column of a table. When I create a primary key constraint I get a syntax error.
Here is a sample sql script I'm using with psql to create the table:
CREATE TYPE my_type AS
(
field1 integer,
field2 integer
);
CREATE TABLE my_table
(
my_data my_type,
other_data integer
);
ALTER TABLE my_table ADD CONSTRAINT pk_my_table PRIMARY KEY (my_data.field1);
I get this error:
ERROR: syntax error at or near "."
LINE 1: ...ble ADD CONSTRAINT pk_my_table PRIMARY KEY (my_data.field1);
I've tried using (my_data).field1 but also get a syntax error.
If I just use my_data in the constraint there is no error:
ALTER TABLE my_table ADD CONSTRAINT pk_my_table PRIMARY KEY (my_data);
But I would like to use just one field as part of the constraint.
Thanks for any ideas.
I found this question using google and I'm pretty sure is dead but I still want to answer it cause someone else might see it.
Short answer is you have to use the field's name:
ALTER TABLE "public"."carga" ADD CONSTRAINT "pk_my_table" PRIMARY KEY ("field1");