Setting constraint so that new value in “Table A” must already exist in “Table B”, else return error?
-
07-02-2021 - |
سؤال
I'm trying to set up some kind of constraint so that I can only enter values in "Table A", if that value exists in "Table B".
I want this to act sort of like a selection list, where there are only a few values that exist in "Table B", which then restricts the values that can be entered into "Table A". (Kind of like a drop down list/ selection list)
I'm using pgAdmin 4 to access a PostGIS DB
المحلول
Sounds like you want a FOREIGN KEY
constraint!
You should do something like this:
CREATE TABLE B (primary_key_value INTEGER PRIMARY KEY... other fields);
CREATE TABLE A (primary_key_field PRIMARY KEY, foreign_key_value INTEGER, other fields...
CONSTRAINT 'name_of_fk_constraint'
FOREIGN KEY (foreign_key_value) REFERENCES B (primary_key_value);
If you try to INSERT
a record into table A and the foreign_key_value field doesn't contain the value you're trying to insert in table B's PRIMARY KEY
field (it can also be UNIQUE
and NOT NULL
), you will get an error and your INSERT
will fail.
The classic example of this is the orders
table and its child the order_line table.
CREATE TABLE orders (order_id INTEGER PRIMARY KEY, client_id, other_fields...);
CREATE TABLE order_line (order_id, part_name, part_id, other_fields...
CONSTRAINT 'order_id_fk' FOREIGN KEY (order_id) REFERENCES orders (order_id);
The client_id
field in the orders
table could (and indeed should) be a FOREIGN KEY
into the client
table - the critical thing about FORIGN KEY
s is that they establish relationships between the different tables so that you have consistently correct data with the correct client per order and every order_line belongs to one and only one order. Do NOT be tempted to eliminate FOREIGN KEY
s for "so-called" performance reasons - they are VITAL for a functioning database system.