Simple conceptual question

Hi guys, I am a software development student. But sometimes I need to create databases to create my projects. So many times when I created a database and I worked with more than one table with relation fk. When I insert data into the table A with a fk with relation with Table B can’t insert data in the column with the fk then I insert data in the table B, that works obviously but don’t get that new value in the table A. Why thats happen? What is the correct approach?

simple conceptual answer –

when two tables are related with a foreign key, we usually name one of these tables as the parent table, and the other as the child table

the child table contains the foreign key, which references the parent table’s primary key

what usually happens is that a row must already exist in the parent table before a row which references it can be inserted into the child table

so when you insert a row in the child table, you must give the foreign key value, which must reference an existing primary key value in the parent table


Can you give a simple sql example?

I think Rudy gave you good direction to work from. To tie it back to your original example, Table B would be the parent, and Table A would be the child.

So, say your tables are a product and shopping cart. Normally you would name them better, but I’m going with your names above…so your structure could be something like this.

TableB:  PK, Description, Cost
TableA  PK, TableB_FK (which is a foreign key which ties to PK on TableB), ItemCount

if TableB has the following

PK  Description
--- -----------
1   Test 1
2   Test 2
3   Test 3

Then you can add rows to TableA that have 1, 2 or 3 in the TableB_FK field because those values exist on TableB. But you can NOT add a value of 5 in that field because a row with a PK of 5 does not exist in the table, and until one is added to TableB, that value can’t be used in TableA…

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.