0

Let's say there is a database with two tables: one customer table and one country table. Each customer row contains (among other things) a countryId foreign key. Let's also assume that we are populating the database from a data file (i.e., it is not an operator that is selecting a country from a UI).

What is the best practice for this?

  1. Should one query the database first and get all ID's for all countries, and then just supply the (now known) country id's in the insert query? This is not a problem for my 'country' example, but what if there is a large number of records in the table that is being referred?

  2. Or should the insert query use a sub query to get the country id based on the country name? If so, what if the record for the country does not exist yet and has to be added?

  3. Or another approach? Or does it depend? :)

1 Answer 1

1

I would suggest using a join in your insert query to get the country id based on the country name. However, I don't know if that's something possible with every SGBD and you don't give more precision on the one you're using.

Sign up to request clarification or add additional context in comments.

2 Comments

Using mysql. What happens if a record for the country does not already exist? Thank you.
well I would be tempted to say you just have to populate your country table first... but then when speaking about other data it wouldn't be correct. In that case a more programmatic approach would be needed : testing if value exist, if not insert it, then use the new id to populate field in main table.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.