patternsqlModerate
Should arrays of IDs stored in Postgres use varchar, int, or another type?
Viewed 0 times
storedarrayspostgresidsvarchartypeanothershoulduseint
Problem
What is proper convention for creating a field that will hold an array of foreign keys? In this particular case, I'm creating a field called "owners" that will hold an array of user IDs. I want to make sure I choose the right type to maximize speed and follow convention.
Thanks.
Thanks.
Solution
The "one true way" is to create a table and use foreign keys:
That way you can verify membership using a single and simple query:
And you can get a list of owners for an account using:
Alternatively, you can find all accounts a user owns using the reverse query:
CREATE TABLE owners(
user_id int references users
, account_id int references accounts
, primary key(user_id, account_id)
);That way you can verify membership using a single and simple query:
SELECT user_id, account_id FROM owners WHERE user_id = X AND account_id = YAnd you can get a list of owners for an account using:
SELECT user_id FROM owners WHERE account_id = XAlternatively, you can find all accounts a user owns using the reverse query:
SELECT account_id FROM owners WHERE user_id = XCode Snippets
CREATE TABLE owners(
user_id int references users
, account_id int references accounts
, primary key(user_id, account_id)
);SELECT user_id, account_id FROM owners WHERE user_id = X AND account_id = YSELECT user_id FROM owners WHERE account_id = XSELECT account_id FROM owners WHERE user_id = XContext
StackExchange Database Administrators Q#11853, answer score: 12
Revisions (0)
No revisions yet.