Inserting Across Multiple Tables: Techniques and Examples

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

← 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 →

Earn 3 college credits for Database ProgrammingRecommended for credit by NCCRS · Computer Science 381 · self-paced · one payment, lifetime access

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.

Compare: Database Fundamentals vs Database Programming

Why take it here

Why students take Database Programming with UPI Study

Write the SQL behind every appDatabase Programming teaches SQL in MySQL and SQL Server side by side: designing and normalizing tables, keys and constraints, data types, inserting, updating and deleting rows, filtering, grouping, joins, subqueries, views, indexes, transactions, and protecting data from SQL injection. It suits computer science and information technology degrees.
Credit at a fraction of the priceThe same 3 credits can cost $750 or more at a US college. Here it is one payment, self-paced, with lifetime access.
Finish your degree soonerTransfer credits reduce the courses you still owe, so you can graduate earlier or lighten a heavy semester.
Strengthen an applicationA completed college-level course on an official transcript shows admissions and scholarship committees you can do the work.
Study on your own scheduleNo start dates, no deadlines. Watch the lessons, practice, and take the final when you are ready.
130,000+students helped with college creditsACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

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.

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?
Insert the parent rows first, then the child rows that reference them, inside one transaction. From a staging table, INSERT INTO orders (order_id, customer_id) SELECT DISTINCT order_id, customer_id FROM staging; loads each order once, and a second INSERT with SELECT loads its lines. Name the target columns in both statements. Commit only after both succeed, and roll back on any error so a failed line insert cannot leave orders without their items.
How does each child row find its new parent's key during an import?
Insert the parent row first, read its generated key in the same session, and use that value as the foreign key in the child inserts. MySQL's LAST_INSERT_ID() is per connection and, after a multi-row insert, returns only the first generated value. SQL Server's SCOPE_IDENTITY() returns the last identity in the current scope, whereas @@IDENTITY can return a trigger's value. For many parents, join back on a unique business key.
What is the difference between CREATE TABLE AS SELECT and SELECT INTO?
Both create a new table from a query result, but in different systems: MySQL and SQLite write CREATE TABLE orders_copy AS SELECT * FROM orders; while SQL Server writes SELECT * INTO orders_copy FROM orders; Neither is a full definition copy, so primary keys, indexes, foreign keys and triggers must be recreated. SQL Server's SELECT INTO can keep an identity column in a simple copy, and a false condition such as WHERE 1 = 0 creates an empty table.
How do you stop a retried import from inserting duplicate rows?
Insert only source keys that are not already present, and back that up with a unique key. For example, INSERT INTO orders (order_id, customer_id) SELECT DISTINCT s.order_id, s.customer_id FROM staging s WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.order_id = s.order_id); adds new orders only, so replaying a batch creates nothing twice. Concurrent retries still need suitable transaction handling, and the unique key catches anything the check misses.

About the Database Programming course

How many college credits is Database Programming?
Database Programming (Computer Science 381) carries a NCCRS credit recommendation for 3 semester credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
How much does Database Programming cost and what is included?
$250, paid once, with lifetime access: all 76 video lessons, a practice quiz after each, the graded work and final exam, and an official transcript when you finish. Students who want several courses choose UPI Study PRO instead.
Which universities accept UPI Study credits?
UPI Study has signed partner agreements with universities such as Thomas Edison State University, University of the People and Charter Oak State College, and works with universities such as Penn State, SNHU and SUNY. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities. Use "Find my college" on this page to check yours.
How long does Database Programming take?
It is self-paced with no deadlines. The 76 lessons total about 11 hours of video; most students add reading and practice time and finish in a few weeks to a few months, on their own schedule.
How are the exams done?
Quizzes and assignments are online in the course. The final exam is taken online with proctoring; a person on the UPI Study team checks assignments, usually within two days.
How do my credits reach my college?
When the course shows 100% complete, request the official transcript from your dashboard. It is sent to the college you name, and you can send it to more than one. Check your college first with "Find my college" on this page, or ask Athena.

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

Database Programming
3 credits · NCCRS
Enroll →