I have a table in my database (TableA) that has a column (TableA.Column1) that only allows values from certain rows of another table (TableB.Column2). This is very similar to a normal foreign key relation except for the fact that only certain rows from TableB.Column2 are allowed. For example, I may only allow rows from TableB.Column2 where TableB.Column3 > 100;
Is there a way to express this type of referential integrity in a database? I've tried adding a where clause to a foreign key and I've tried adding a subquery to a Check constraint. I've not gotten either to work.
Does anyone have any advice?
If you are inserting data into a dependent table with foreign keys: Each non-null value you insert into a foreign key column must be equal to some value in the corresponding parent key of the parent table. If any column in the foreign key is null, the entire foreign key is considered null.
The SQL WHERE clause is used to specify a condition while fetching the data from a single table or by joining with multiple tables. If the given condition is satisfied, then only it returns a specific value from the table. You should use the WHERE clause to filter the records and fetching only the necessary records.
A FOREIGN KEY is a field (or collection of fields) in one table, that refers to the PRIMARY KEY in another table. The table with the foreign key is called the child table, and the table with the primary key is called the referenced or parent table.
A query can contain both a WHERE clause and a HAVING clause. In that case: The WHERE clause is applied first to the individual rows in the tables or table-valued objects in the Diagram pane. Only the rows that meet the conditions in the WHERE clause are grouped.
The answer may differ depending on the database system you are using. But an option is certainly to use a trigger.
If you only allow "certain" values that are held in a column from Table A, you could create a composite FK in Table B, then add a separate check constraint in your table (Table B)? Though, this sounds like the kind of thing I would enforce in the application tier.
No, I don't think there's any way to do this.
What I typically end up doing in cases like this is create a "dummy" entry (e.g. something like ID = -1, Text = "state or entry unknown"
) into the table being referenced, and then setting those TableB.Column2
values to this dummy ID value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With