Question

I am trying to make a constraint that will keep ids unique for specific users.
Each user is a separate entity within the world so 2 people having 1 as id is not a problem. I just don't want one person to have the same id twice.

For example: This would be acceptable:

User   Id
John   1
John   2
Alice  1
Alice  2

This would not be ok:

User     Id
John     1
John     1  -- problem
Alice    1
Alice    2
Was it helpful?

Solution

Just add a Unique constraint over both columns to your CREATE TABLE statement:

CREATE TABLE person(
   ...               -- more columns
   username text 
  ,person_id int
  ,UNIQUE (username, person_id)
);

That does it. I see that @Hamlet and @Frank already commented likewise.

OTHER TIPS

Creating a unique index on these two columns would also work. This is usually what happens under the covers to enforce the constraint.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top