INSERT with SELECT statement for columns with FOREIGN KEY constraint in MySQL with examples.

Joshua Otwell
codeburst
Published in
6 min readJul 4, 2018

--

In this blog post, we’ll look at an example of INSERT with SELECT syntax to honor those FOREIGN KEY constraints we have in place that ensure referential integrity between rows in separate tables.

Photo by Fahrul Azmi on Unsplash

Note: All data, names or naming found within the database presented in this post, are strictly used for practice, learning, instruction, and testing purposes. It by no means depicts actual data belonging to or being used by any party or organization.

OS and DB used:

  • Xubuntu Linux 16.04.3 LTS (Xenial Xerus)
  • MySQL 5.7.22

* Note: Both of the tables used in this blog post are a semblance of examples found in a fantastic PHP & MySQL book I am studying/learning from as I am exploring developing my skill-set in that back-end technology area. Therefore, all credit of design and idea goes to that author and are not of my original planning or creation. I have slightly altered some of the table and column naming for my benefit and understanding. As of this writing, the book has not instructed or recommended the FOREIGN KEY constraints I use in this blog post, I have implemented them of my own accord.

First, let’s get a description of each table.
The author table:

mysql> SHOW CREATE TABLE author\G
*************************** 1. row ***************************
Table: author
Create Table: CREATE TABLE `author` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`author_name` varchar(255) DEFAULT NULL,
`author_email` varchar(255) DEFAULT NULL,
KEY `id` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8
1 row in set (0.00 sec)

And the joke table:

mysql> SHOW CREATE TABLE joke\G
*************************** 1. row ***************************
Table: joke
Create Table: CREATE TABLE `joke` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`joke_text` text,
`joke_date` date DEFAULT NULL,
`author_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `joke_ibfk_1` (`author_id`),
CONSTRAINT `joke_ibfk_1` FOREIGN KEY (`author_id`) REFERENCES `author` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8
1 row in set (0.00 sec)

We can see there is a FOREIGN KEY in table joke that references column id in table author. So what does this mean and how does this work?

Let’s try this INSERT:

mysql> INSERT INTO joke(joke_text, joke_date, author_id)
-> VALUES (‘Mary had a little lamb’, ‘1909–08–15’, 5);
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`homestead`.`joke`, CONSTRAINT `joke_ibfk_1` FOREIGN KEY (`author_id`) REFERENCES `author` (`id`) ON DELETE SET NULL ON UPDATE CASCADE)

Let’s see the id‘s in the author table this error reports to us:

mysql> SELECT id FROM author;
+ — — +
| id |
+ — — +
| 1 |
| 2 |
| 3 |
+ — — +
3 rows in set (0.00 sec)

There is not an id of 5 present, so we cannot INSERT that value into column author_id in the joke table as this is the ‘child table’.
We can only use id 1, 2, or 3 because they exist in table author.
Let’s visit this passage from section 13.1.18.6 Using FOREIGN KEY Constraints in the documentation for understanding: “For storage engines supporting foreign keys, MySQL rejects any INSERT or UPDATE operation that attempts to create a foreign key value in a child table if there is no a matching candidate key value in the parent table”

Let’s INSERT using id 2:

mysql> INSERT INTO joke(joke_text, joke_date, author_id)
-> VALUES (‘Mary had a little lamb’, ‘1909–08–15’, 2);
Query OK, 1 row affected (0.03 sec)

That worked just fine.
The brunt of it is, in order to INSERT a record in table joke, the author_id column value must exist in table author.
Let’s INSERT a new author in table author:

mysql> INSERT INTO author(author_name, author_email)
-> VALUES(‘Famous Anthony’, ‘fam@fame.org’);
Query OK, 1 row affected (0.05 sec)

Then let’s see that row we just added:

mysql> SELECT * FROM author
-> WHERE author_name = ‘Famous Anthony’;
+ — — + — — — — — — — — + — — — — — — — +
| id | author_name | author_email |
+ — — + — — — — — — — — + — — — — — — — +
| 4 | Famous Anthony | fam@fame.org |
+ — — + — — — — — — — — + — — — — — — — +
1 row in set (0.00 sec)

Now we are able to use that author’s id in an INSERT for table joke.
Suppose though, we don’t know firsthand the author’s id when inserting into table joke?
But we do know the author name (which needs to be present in table author mind you).
We can INSERT that column value using a SELECT statement.
See this example for clarity:

mysql> INSERT INTO joke(joke_text, joke_date, author_id)
-> VALUES (‘Humpty Dumpty had a great fall.’, ‘1899–03–13’, (SELECT id FROM author WHERE author_name = ‘Famous Anthony’));
Query OK, 1 row affected (0.03 sec)

Let’s check the joke table and the row with the correct id from table author with an INNER JOIN(See my blog post to learn about INNER JOIN‘s in MySQL):

All data is correct in the linking table.

Easy as pie.

In a coming blog post, I’ll mitigate retyping the INSERT with SELECT statement by ‘wrapping’ that operation in a function so be sure and visit that post also!

Explore the official MySQL 5.7 On-line Manual for questions and more information.

A Call To Action!

Thank you for taking the time to read this post. I truly hope you discovered something interesting and enlightening. Please share your findings here, with someone else you know who would get the same value out of it as well.

Visit the Portfolio-Projects page to see blog post/technical writing I have completed for clients.

Have I mentioned how much I love a cup of coffee?!?!

To receive email notifications (Never spam) from this blog (“Digital Owl’s Prose”) for the latest blog posts as they are published, please subscribe (of your own volition) by clicking the ‘Click To Subscribe!’ button in the sidebar on the homepage! (Feel free at any time to review the Digital Owl’s Prose Privacy Policy Page for any questions you may have about: email updates, opt-in, opt-out, contact forms, etc…)
Be sure and visit the “Best Of” page for a collection of my best blog posts.

Josh Otwell has a passion to study and grow as a SQL Developer and blogger. Other favorite activities find him with his nose buried in a good book, article, or the Linux command line. Among those, he shares a love of tabletop RPG games, reading fantasy novels, and spending time with his wife and two daughters.

Disclaimer: The examples presented in this post are hypothetical ideas of how to achieve similar types of results. They are not the utmost best solution(s). The majority, if not all, of the examples provided are performed on a personal development/learning workstation-environment and should not be considered production quality or ready. Your particular goals and needs may vary. Use those practices that best benefit your needs and goals. Opinions are my own.

Originally published at joshuaotwell.com on July 4, 2018.

✉️ Subscribe to CodeBurst’s once-weekly Email Blast, 🐦 Follow CodeBurst on Twitter, view 🗺️ The 2018 Web Developer Roadmap, and 🕸️ Learn Full Stack Web Development.

--

--

SQL | PHP | Photography. Sign-up for my free developer newsletter, OpenLampTech, here: openlamptech.substack.com