create table sequenced_message ( id text not null primary key, sequence bigint not null, channel text not null references channel (id), sender text not null references login (id), body text not null, sent_at text not null, unique (channel, sequence) ); insert into sequenced_message select id, rank() over ( partition by channel order by sent_at ) as sequence, channel, sender, body, sent_at from message; drop table message; alter table sequenced_message rename to message; create index message_sent_at on message (channel, sent_at);