Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constraint for one-to-many relationship

We have a two tables with a one-to-many relationship. We would like to enforce a constraint that at least one child record exist for a given parent record.

Is this possible?

If not, would you change the schema a bit more complex to support such a constraint? If so how would you do it?

Edit: I'm using SQL Server 2005

like image 318
George Avatar asked Feb 28 '23 20:02

George


2 Answers

Such a constraint isn't possible from a schema perspective, because you run into a "chicken or the egg" type of scenario. Under this sort of scenario, when I insert into the parent table I have to have a row in the child table, but I can't have a row in the child table until there's a row in the parent table.

This is something better enforced client-side.

like image 162
Adam Robinson Avatar answered Mar 08 '23 15:03

Adam Robinson


It's possible if your back-end supports deferrable constraints, as does PostgreSQL.

like image 24
Kev Avatar answered Mar 08 '23 17:03

Kev