Using primary keys in postgrSQL [duplicate] - postgresql

This question already has answers here:
What is a PRIMARY KEY
(4 answers)
Closed 2 years ago.
I currently have a table:
userID | color | quantity
-------------------------
where userID is the primary key. My problem is when I try to insert to the DB (that already has one item from the same ID) I get the error: pq: duplicate key value violates unique constraint I am using Go with lib/pq package to insert.
I am unsure whether I have the wrong idea of what to use a PK for, or if I don't understand what kind of table I need to make

Primary key is a key that uniquely identifies each single row in the table and therefore needs to be unique. If you need more rows with same userID in your table then userID cannot be a primary key.
When you specify column (or group of columns) as a primary key PostgreSQL will put uniqueness constraint on it so it cannot happen that two rows in table have same contents of that column - that's why you see constraint violation error.
You can solve this problem by adding another ID column that will have unique value for each row (e.g. autoincremented sequence) and making it primary key instead of userID.
Here is a detailed tutorial on primary key in Postgres to give you a better understanding of primary key usage.

Related

PostgreSQL declarative partition - unique constraint on partitioned table must include all partitioning columns [duplicate]

This question already has an answer here:
ERROR: unique constraint on partitioned table must include all partitioning columns
(1 answer)
Closed last month.
I'm trying to create a partitioned table which refers to itself, creating a doubly-linked list.
CREATE TABLE test2 (
id serial NOT NULL,
category integer NOT NULL,
time timestamp(6) NOT NULL,
prev_event integer,
next_event integer
) PARTITION BY HASH (category);
Once I add primary key I get the following error.
alter table test2 add primary key (id);
ERROR: unique constraint on partitioned table must include all partitioning columns
DETAIL: PRIMARY KEY constraint on table "test2" lacks column "category" which is part of the partition key.
Why does the unique constrain require all partitioned columns to be included?
EDIT: Now I understand why this is needed: https://www.postgresql.org/docs/current/ddl-partitioning.html#DDL-PARTITIONING-DECLARATIVE-LIMITATIONS
Once I add PK with both columns it works.
alter table test2 add primary key (id, category);
But then adding the FK to itself doesn't work.
alter table test2 add foreign key (prev_event) references test2 (id) on update cascade on delete cascade;
ERROR: there is no unique constraint matching given keys for referenced table "test2"
Since PK is not just id but id-category I can't create FK pointing to id.
Is there any way to deal with this or am I missing something?
I would like to avoid using inheritance partitioning if possible.
EDIT2: It seems this is a known problem. https://www.reddit.com/r/PostgreSQL/comments/di5mbr/postgresql_12_foreign_keys_and_partitioned_tables/f3tsoop/
Seems that there is no straightforward solution. PostgreSQL simply doesn't support this as of v14. One solution is to use triggers to enforce 'foreign key' behavior. Other is to use multi-column foreign keys. Both are far from optimal.

PostgreSQL oximoron

Hi all,
Can any understand what's going on here?
The case is:
There are 2 tables, called "matricula" and "pagament" with a 1:1 relationship cardinality.
Table matricula primary key composed by 3 fields "edicio","curs" and "estudiant".
Table pagament primary key, the same as above. Furthermore, it references matricula.
As shown, trying to insert a row in pagament table is rejected because it does not exists a row in table matricula. However, asking for this row returns one result.
What am I missing?
Thanks you all
Carles
The problem is that the order of the fields in both tables is not the same, and, moreover, the restriction of the foreign key in table pagament, said that
foreign key (estudiant,curs,edicio) references matricula
without specifying the matricula fields.
It's been solved by setting this restriction as
foreign key (estudiant,curs,edicio) references matricula(estudiant,curs,edicio)

Is a primary key field NOT NULL by default in postgres? [duplicate]

This question already has answers here:
Why can I create a table with PRIMARY KEY on a nullable column?
(5 answers)
Closed 1 year ago.
Is a primary key field NOT NULL by default in postgres, or does it need to be specified as such when creating the table?
Quote from the manual
Adding a primary key will automatically create a unique B-tree index on the column or group of columns listed in the primary key, and will force the column(s) to be marked NOT NULL.
(emphasis mine)

How to efficiently add an auto-incrementing primary key to an existing column in postgres? [duplicate]

This question already has answers here:
PostgreSQL, reconfigure existing table, changing primary key to type=serial
(1 answer)
How to convert primary key from integer to serial?
(1 answer)
Closed 3 years ago.
Problem
I can add an auto-incrementing primary key to a pre-existing column in an empty table in postgres, but I wonder if it can be done more efficiently.
What I've Done
Before the table gets populated, I need to alter a column to add an auto-incrementing primary key. Similar to the answer to this question, the following will work (assuming the table is named test and the column in question is named col1):
ALTER TABLE test ADD PRIMARY KEY (col1);
CREATE SEQUENCE seq OWNED BY test.col1;
ALTER TABLE test ALTER COLUMN col1 SET DEFAULT nextval('seq');
UPDATE test SET col1 = nextval('seq');
Four lines is far from the end of the world. However, as per that answer, this can be done in one line if we're adding a column rather than altering a pre-existing one:
ALTER TABLE test ADD COLUMN col1 SERIAL PRIMARY KEY;
Question
Is there a way to do that in one line, but for a pre-existing column? It seems like SERIAL is limited to when one adds a new column, but I figured it can't hurt to ask. My naive attempts included things like:
ALTER TABLE test ALTER COLUMN col1 SERIAL PRIMARY KEY;
ALTER TABLE test ADD SERIAL PRIMARY KEY (col1);
Thanks!
EDIT: This got marked as a duplicate right off the bat, though I read both of those questions coming into this. I feel like they both use the same methodology that I'm already using (unless I misunderstood what was at play), and my question is about seeing if there's a more efficient way to do it, especially since there is in new column creation.

Why does this foreign key using inheritance not work? [duplicate]

This question already has answers here:
PostgreSQL foreign key not existing, issue of inheritance?
(2 answers)
Closed 8 years ago.
create table abstract_addresses (
address_id int primary key
);
create table phone_numbers (
phone_number text not null unique
) inherits (abstract_addresses) ;
create table contacts (
name text primary key,
address_id int not null references abstract_addresses(address_id)
);
insert into phone_numbers values (1, '18005551212'); --works
select * from abstract_addresses;
address_id
1
select * from phone_numbers;
address_id phone_number
1 18005551212
insert into contacts values ('Neil', 1); --error
I get this error message:
ERROR: insert or update on table "contacts" violates foreign key constraint "contacts_address_id_fkey"
SQL state: 23503
Detail: Key (address_id)=(1) is not present in table "abstract_addresses".
Just a bad use-case for postgresql table inheritance?
Per the caveats in the docs:
A serious limitation of the inheritance feature is that indexes (including unique constraints) and foreign key constraints only apply to single tables, not to their inheritance children. This is true on both the referencing and referenced sides of a foreign key constraint.
http://www.postgresql.org/docs/current/static/ddl-inherit.html
To do what you want:
Create a table with only an id — like you did.
Don't use inheritance. Really don't. It's useful to partition log tables; not for what you're doing.
Make phone number ids default to nextval('abstract_addresses_address_id_seq'), or whatever the sequence name is.
Add a foreign key in phone_numbers referencing abstract_addresses (address_id). Make it deferrable, initially deferred.
Add an after insert trigger on phone_numbers that inserts a new row in abstract_addresses when needed.
If appropriate, add an after delete trigger on phone_numbers that cascade deletes abstract_addresses — make sure it occurs after the delete, else affected rows will report incorrect values when you delete from phone_numbers.
That way, you'll have an abstract_address for use in occasional tables that need such a thing, while still being able to have a hard reference to phone_numbers where the latter is what you actually want.
One caveat to be aware of: it doesn't play well with ORMs.