HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlModerate

Should arrays of IDs stored in Postgres use varchar, int, or another type?

Submitted by: @import:stackexchange-dba··
0
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.

Solution

The "one true way" is to create a table and use foreign keys:

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 = Y


And you can get a list of owners for an account using:

SELECT user_id FROM owners WHERE account_id = X


Alternatively, you can find all accounts a user owns using the reverse query:

SELECT account_id FROM owners WHERE user_id = X

Code 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 = Y
SELECT user_id FROM owners WHERE account_id = X
SELECT account_id FROM owners WHERE user_id = X

Context

StackExchange Database Administrators Q#11853, answer score: 12

Revisions (0)

No revisions yet.