Pregunta

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
¿Fue útil?

Solución

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.

Otros consejos

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

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top