Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
351 views
in Technique[技术] by (71.8m points)

postgresql - Do I need to declare a unique constraint for `bigint generated always as identity`?

I'm creating a multi-tenant application and am prepending the tenant_id to all tables that my tenants will access. All of the tables will also have an incrementing surrogate key. Will I need to declare a unique constraint of the surrogate key or is that redundant?

CREATE TABLE tenant (
  primary key (tenant_id),
  tenant_id  bigint generated always as identity
);

CREATE TABLE person (
  primary key (tenant_id, person_id)
  person_id  bigint generated always as identity,
  tenant_id  bigint not null,

  unique (person_id),  -- Do I need this?

  foreign key (tenant_id) references tenant
);
question from:https://stackoverflow.com/questions/65947502/do-i-need-to-declare-a-unique-constraint-for-bigint-generated-always-as-identit

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The primary key of a table should be a minimal set of columns that uniquely identify a table row. So that should be person_id, as it was specifically created for that purpose.

Add another (non-unique) index on tenant_id or (tenant_id, person_id) if you need to speed up searches based on tenant_id.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...