Quantcast
Channel: Question and Answer » postgresql
Viewing all articles
Browse latest Browse all 1138

Foreign key with additional constraints?

$
0
0

There is a table called Item(id, name, cost) and Orders(id, bill_id, item_id, units), which is created to track orders placed, where same bill_id means it belongs to a single order.

How to impose an additional constraint in DB that says Item should be “Available” (at that point of time) if it needs be to added as item_id in the Order table? An item is manually determined as “Available” and can’t be derived from other fields in the database in this scenario.

One schema design (I prefer) is to add a Type column which would have “Available” and “Unavailable” fields. But how can I check the Foreign Key constraint item_id should not only be a Primary Key in Item table, its Type should be “Available” as well?

This Stack Overflow answer using check constraints seems close, but is that the only way? I feel this is a trivial thing for RDBMS, or is this is not a normalized data?

The other schema design (I don’t prefer) is to have a Table called “Menu” which could have only the Items Available. The problem is that this table is going to very dynamic in nature and it keeps changing depending on the availability of items. And, I am just creating a subset table out of Items depending on its state which doesn’t seem to be a nice idea.

It’s easy to do this programmatically; however, how do I achieve this in RDBMS? I like the idea of Database being intelligent enough to handle this.


Viewing all articles
Browse latest Browse all 1138

Trending Articles