0
  1. I have 2 tables Parent and Child.

  2. Child has a unique attribute(childNo)

  3. As long as 2 Children have different Parents, they should be able to have the same childNo.

  4. 2 Children with the same Parents should not have the same childNo

I can't think of a way to implement this as I'm getting a unique constraint violation.

enter image description here

Tom Taylor
  • 3,344
  • 2
  • 38
  • 63

1 Answers1

1

Use a multicolumn UNIQUE index or constraint on child (childNo, parent_id).

This way, the same combination of (childNo, parent_id) cannot be entered a second time. That's all you need.
(Might also serve as PRIMARY KEY, replacing the additional child.id, but that depends ...)

If child.parent_id can be NULL (and you don't want two rows with the same childNo and NULL), consider:

And avoid CaMeL-case identifiers in Postgres to make your life easier. See:

Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228