UPI Study › Courses › Database Programming › Free lessons › Lesson 11.4 Free with a free account
Inserting Across Multiple Tables: Techniques and Examples
Database Programming · Chapter 11: Advanced Data Operations and Pattern MatchingSection 11.4 · lesson 67 of 769 min · free with a free account
Free preview
Create a free account to keep watching
It takes a minute and costs nothing. Your free account unlocks all of Chapter 1 and 3 more lessons of Database Programming.
Lesson complete
Earn the 3 college credits for Database Programming
Enrolling adds a quiz after each lesson, the graded work and the official transcript. Recommended for credit by NCCRS.
Next lesson: Reshaping Data with PIVOT and UNPIVOT →← Advanced Data Manipulation Using SubqueriesNext lesson: Reshaping Data with PIVOT and UNPIVOT →
A free account plays all of Chapter 1 and 3 more lessons of Database Programming. Create a free account →
In this lesson
Load parent and child tables together with INSERT SELECT and transactions.
- Use INSERT SELECT to distribute staged rows into parent and child tables
- Retrieve generated keys correctly in SQLite, MySQL and SQL Server
- Explain what CREATE TABLE AS SELECT and SELECT INTO do not copy
- Wrap a multi-table load in a transaction with a rollback path
Free study notes
Get this lesson's notes by email
The key points and 4 practice questions with answers, in your inbox. One email, free.
One email. Unsubscribe in one click.
Transcript
Everything said in the video, section by section (1,119 words). Read along, or search it.
Opening Scenario
One Import Feeding Two Related Tables
Leo Park, Lantern Books' application developer, receives one import containing orders and book lines. Each line needs an existing customer and the correct parent order. If the parent insert succeeds but the line insert fails, should half the import remain? And how will each child find its parent's key? We'll split a small staging file into related tables, then examine generated keys, table copies, retries, and transaction boundaries.
Sandbox Setup
Customers, Products, Orders and Order Items
Our scratch schema projects the existing customers Asha and Chen, plus Database Basics and Notebook. Their identifiers retain their canonical meanings. Orders are parents of order items, and also children of customers. An insert sequence must respect every foreign-key dependency. These projections omit unrelated attributes. Quantity checks reject invalid counts, and the composite item key prevents duplicate product lines. Run the setup in SQLite. Foreign-key checking is enabled explicitly, before the transaction that will perform the import.
Staging Table
Incoming Lines Before Distribution
A staging table holds incoming records before they are distributed into final tables. These invented new order numbers are reserved for this sandbox import. The first order appears on two lines, because it contains two products. Repeating its parent information does not mean we should insert two parent orders. Our target column lists will name the intended destinations. Each select must supply the same number of compatible values, in the same positional order. Run the staging script. Inspect the incoming rows, rather than treating a successful file read as proof that the data is valid. Three source lines describe two orders. Before loading, also check missing parents and conflicting customer identifiers for the same order number.
INSERT SELECT
Load Parents First, Then Child Lines
Insert select takes its rows from a query. Distinct collapses repeated parent information, then a second insert loads the corresponding child lines. Name the target columns explicitly. Generated columns can be omitted when the database supplies them, but these imported order identifiers are stable source keys. The parent insert comes first, and commit comes after both inserts. Constraint failures require the application's error path to roll back instead of continuing to commit. Run the valid load. This particular rehearsal succeeds, so the commit keeps both the orders and their product lines. The three child lines point to two parents. An inner join can silently omit unmatched input; reconcile source counts and reject missing mappings before committing.
Quick Check
A Replayed Source Key Is Skipped
A new loader already holds source key seventy. Its incoming batch contains seventy and seventy-one, and the statement excludes keys already present. How many records exist afterward? Pause, and predict whether replaying a source key creates another record. Two records exist. The guard skips the existing source key, while the new key is inserted once. Run the miniature loader. A unique key enforces the rule, while not exists explains which input rows should be attempted. The count is two. One would miss the new input, while three would duplicate the old key; concurrent retries still need suitable transaction handling.
Table Copies
CREATE TABLE AS SELECT Versus SELECT INTO
CREATE TABLE AS SELECT makes a new table from query output. SQLite and MySQL use this form; SQL Server instead uses SELECT INTO. A data copy is not a full definition copy or a backup. Check keys, constraints, indexes, triggers, defaults, and identity behavior separately. MySQL CREATE TABLE LIKE copies more structure without rows, but does not copy foreign keys. SQL Server can retain identity in a simple SELECT INTO. Run the copy and inspect its row count and primary-key metadata. Matching data does not imply matching integrity rules. Three rows were copied, but no primary-key columns were declared in the copy. Recreate the required rules before relying on it as an operational table. These non-run listings contrast the two server spellings. MySQL CREATE TABLE LIKE creates structure only, while a later INSERT SELECT can copy rows. In SQL Server, a false predicate makes SELECT INTO create an empty table. Its column definitions still come from the query result. Identity preservation has exceptions, including joins, unions, and expressions. Inspect the destination schema, rather than assuming a query copy preserves every source property.
Generated Keys
Capturing a New SQLite Batch Key
For a generated-key example, add a separate import-batch parent and receipt child. SQLite's integer primary key generates the batch identifier when we omit it. Capture last_insert_rowid() immediately, before another insert changes it. Our temporary mapping stores the generated parent key, then supplies it to the receipt. This demonstrates key transfer, not a portable identity function. MySQL uses AUTO_INCREMENT, and SQL Server uses identity with different retrieval functions. Run the SQLite example. It creates one batch, captures its key, and uses that actual value in the related receipt. The receipt points to batch one. Never calculate future keys from this result; generated values can have gaps and differ across systems.
Server Functions
LAST_INSERT_ID, SCOPE_IDENTITY and OUTPUT
MySQL's LAST_INSERT_ID is connection-local. After a multi-row insert, it gives the first generated value, not a complete mapping of all new rows. SQL Server SCOPE_IDENTITY returns the last identity in the current scope. @@IDENTITY includes trigger scopes, and IDENT_CURRENT can include other sessions. For many rows, join back on a validated unique business key, or capture keys with SQL Server's output clause. Pair keys with labels, not output positions. Output row order is not guaranteed, and returned keys do not prove commit. Sorting input also does not guarantee the same generated identifiers on every load.
Second Check
Rollback Removes Parent and Child
A separate trial inserts one parent and one child inside a transaction. The application then deliberately rolls it back, rather than committing. How many rows remain in the two tables? Answers read parent count, then child count. Pause, and predict the result of the explicit rollback. Zero and zero remain. Rollback undoes both inserts, because they belong to the same uncommitted transaction. Run this independent trial. Both table definitions were created before begin, so this question concerns only the two transactional inserts. Both counts are zero. Keeping the parent would break the requested all-or-nothing boundary, while keeping both would describe a commit.
Error Handling
Rolling Back When a Load Fails
SQL Server combines a transaction with TRY...CATCH and deliberate rollback handling. XACT_ABORT changes runtime-error behavior, and throw reports the failure after cleanup. For MySQL transactional tables, the application or a stored-procedure handler must issue rollback on failure. Create ordinary tables before starting the load transaction. Ordinary MySQL create table causes an implicit commit. Temporary create table is an exception, but its creation is not undone by rollback. Leo's complete load therefore includes validation, key mapping, and an error path. Generated-key gaps are acceptable; incomplete parent-child relationships are not.
Key Takeaways
Commit Only the Complete Unit
Leo uses INSERT SELECT to distribute staged rows, with explicit target columns. Parents exist before children, and every source row receives a checked mapping. He treats table copies as new structures to inspect. Generated keys travel through captured mappings or unique-key lookups, never guessed positions. The import commits only when the complete unit succeeds. Rollback handling and the target server's definition-statement rules determine whether that boundary holds.
About Database Programming at UPI Study
Database Programming (Computer Science 381) is a self-paced online course of 76 video lessons in 12 chapters, from database applications, SQL setup, schema planning and normalization to keys and constraints, data types, filtering and sorting, joins, subqueries, views, indexes, ROLLUP and PIVOT, regular expressions and database security. It carries a NCCRS credit recommendation for 3 semester credits.
Every lesson transcript is free on pages like this one, and the videos are free with a free UPI Study account. Enrolling adds a practice quiz after each lesson, the graded work and final exam that earn the credit, lifetime access, and an official transcript on completion. UPI Study has helped over 130,000 students with college credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
Enroll now → Course details Download the syllabus All Computer Science courses Every credit course with PRO →
Why take it here
Why students take Database Programming with UPI Study
Where the credit goes
Universities that work with NCCRS
Database Programming carries a NCCRS credit recommendation. These universities work with NCCRS; some are UPI Study's signed partners. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
Thomas Edison State UniversitySigned partner
University of the PeopleSigned partner
Charter Oak State CollegeSigned partner
Strayer UniversitySigned partner
Columbia Southern UniversitySigned partner
Indiana TechSigned partner
Penn StateWorks with NCCRS
Southern New Hampshire UniversityWorks with NCCRS
SUNYWorks with NCCRS
+many more cooperating universitiesFind my college →Find my college → Not listed? Ask Athena in the corner of this page, or book a 15-minute call.
FAQ
Questions students ask us
About Inserting Across Multiple Tables: Techniques and Examples
How do you insert data into multiple related tables in SQL?
How does each child row find its new parent's key during an import?
What is the difference between CREATE TABLE AS SELECT and SELECT INTO?
How do you stop a retried import from inserting duplicate rows?
About the Database Programming course
How many college credits is Database Programming?
How much does Database Programming cost and what is included?
Which universities accept UPI Study credits?
How long does Database Programming take?
How are the exams done?
How do my credits reach my college?
Ready for the full course? Earn 3 credits in Database Programming.
76 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.
Updated
3 credits · NCCRSEnroll →