PostgreSQL – Unique ID for Row of a Set in One Table

postgresqlprimary-keyunique-constraint

I know the title is a little weird but what I actually want to do is simple. In my Postgres db a user creates a profile and uploads an image.

user_id: 1, photo_id: 1 

Now a second user makes a profile and uploads two images.

user_id: 2, photo_id: 1, photo_id: 2

In my photos table, how can a create a unique identifier out of the combination of user_id and photo_id? Neither are unique in the table but their combination should be.

Best Answer

First, photo_id should be unique on the table. Ignoring sound practice however, you can still do this with a composite PRIMARY KEY

CREATE TABLE photos (
  user_id  int,
  photo_id int,
  PRIMARY KEY (user_id, photo_id)
);

INSERT INTO photos (user_id,photo_id) VALUES (1,1),(1,2);

--duplicate already exists
INSERT INTO photos (user_id,photo_id) VALUES (1,1);

Composite natural PRIMARY KEY's are not bad, however I'm not a fan of having them on multiple surrogate keys. If you're going to create an ID, may as well make it unique.