This table containg user’s photos (thumbnails and full).
Most of queries will have a “WHERE user_id = ?” condition.
CREATE TABLE photos (
"photo_id" serial, -- serial is postgres' autoincrement
"user_id" integer not null, -- foreign key to users table
"filename_thumbnail_50" varchar not null,
"filename_thumbnail_75" varchar not null, -- 75px x 75px thumbnail
"filename_full" varchar not null,
PRIMARY KEY ("photo_id", "user_id")
);
What’s the best design and/or performance design for this usecase:
– Two columns primary key like the above example ?
– One primary key (photo_id) and an index on user_id ?
The primary key should follow your business rules and nothing else. As a photo as such does not have a “real” (i.e. natural) primary key, using a serial as the PK absolutely makes sense.
Extending the primary key with
user_iddoes not make any sense and does not serve any purpose (as thephoto_idwill be unique anyway, you only add overhead to the index maintainence). And with theuser_idbeing the second column in the index it is very unlikely it will be used for a query that limits onuser_id(not impossible but unlikely)So I would go stick with the PK on
photo_idand add an index onuser_id(it’s always a good idea to index foreign key columns anyway).