Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL array of elements that each are a foreign key

I am attempting to create a DB for my app and one thing I'd like to find the best way of doing is creating a one-to-many relationship between my Users and Items tables.

I know I can make a third table, ReviewedItems, and have the columns be a User id and an Item id, but I'd like to know if it's possible to make a column in Users, let's say reviewedItems, which is an integer array containing foreign keys to Items that the User has reviewed.

If PostgreSQL can do this, please let me know! If not, I'll just go down my third table route.

like image 620
Zach Avatar asked Dec 09 '16 06:12

Zach


People also ask

Can we have array for foreign key in PostgreSQL?

Not possible, but might be in the future. Foreign Key Arrays is a work in progress in PostgreSQL. Alternatively, you can do the usual approach of creating a junction(or join) table for this.

How do you check if column is foreign key in Postgres?

Issue \d+ tablename on PostgreSQL prompt, in addition to showing table column's data types it'll show the indexes and foreign keys.


2 Answers

It may soon be possible to do this: https://commitfest.postgresql.org/17/1252/ - Mark Rofail has been doing some excellent work on this patch!

The patch will (once complete) allow

CREATE TABLE PKTABLEFORARRAY (
    ptest1 float8 PRIMARY KEY,
    ptest2 text
);
CREATE TABLE FKTABLEFORARRAY (
    ftest1 int[],
    FOREIGN KEY (EACH ELEMENT OF ftest1) REFERENCES PKTABLEFORARRAY,
    ftest2 int
);

However, author currently needs help to rebase the patch (beyond my own ability) so anyone reading this who knows Postgres internals please help if you can.

like image 82
Jarym Avatar answered Oct 19 '22 18:10

Jarym


No, this is not possible.

PostgreSQL is a relational DBMS, operating most efficiently on properly normalized data models. Arrays are - by definition, they are ordered sets - not relational data structures and the SQL standard therefore does not support defining foreign keys on array elements, and neither does PostgreSQL.

You can, however, build a perfectly fine database with array elements linking to primary keys in other tables. Those array elements, however, can not be declared to be foreign keys and the DBMS will therefore not maintain referential integrity.

like image 118
Patrick Avatar answered Oct 19 '22 19:10

Patrick