When the primary key is also the foreign key, in Postgres
Primary key & Foreign key
Can I designate that one column of a child to be both a foreign key and also a primary key?
Yes absolutely:
create table photo
(
id integer primary key,
... other columns ...
);
create table thumbnail
(
id integer primary key references photo,
... other columns ...
);
TOAST
bytea
columns are stored outside of the normal column data (in so called "toast tables") and are not retrieved unless you include them in the SELECT list.
Quote from the manual
The big values of TOASTed attributes will only be pulled out (if selected at all) at the time the result set is sent to the client.
This only means that even if a query is forced to do a Seq Scan, the bytea columns are not retrieved until the rows are identified that need to be sent back. So if your query does a seq scan on 1 million rows but only 1 row is returned, only one bytea value is read and sent to the client.
Note that the thumbnails might actually be stored inline (not in the toast table) if they are small enough (TOASTing is only triggered for sizes below approx. 2k)
Columns are toasted individually, so there is no problem with keeping both images in a single table. Only the image that appears in the SELECT
list will be detoasted.
Moreover, if an UPDATE
does not affect the toasted columns, they won't have to be rewritten.