Easy-to-follow video tutorials help you learn software, creative, and business skills.Become a member

Using foreign key constraints

From: MySQL Essential Training

Video: Using foreign key constraints

In a relational data base, it's common to have Interconnected with a few rows of data.

Using foreign key constraints

In a relational data base, it's common to have one table refer to another table by its primary key. Problems can arise however if the reference points to a key that doesn't exist. The foreign key constraint is designed to prevent this from happening. We'll be using the scratch database for this lesson and again I'm going to copy from the exercise files. Because well, in this case it actually happens to be a very significant amount of typing.

And the reason for this is that in order to demonstrate the foreign key constraint, we really need to have several tables with different purposes and have them. Interconnected with a few rows of data. And so we have three tables here, a client table, a book table, and a lend table. So the client table just really has a name for the client and an ID. You notice it's integer, AUTO_INCREMENT PRIMARY KEY. And a book table for the books that are going to be lent to the clients, with the title of the book and an ID, very simple tables.

And a lend table and this is what's called a junction table in relational database terminology. The lend table itself has its own ID and it has a time stamp for when the lending happens. And it has. ID tables for the client and the book tables. So c_id is for the client table and b_id is for the book table. And so when we lend a book then a row gets added to the lend table showing the client and the book.

Where the lending transaction and that's called a junction table and of course you don't want to have a book lent to a client that doesn't exist. And you'll notice here that we have three clients, one, two and three because they're auto increment. And three books, one, two, and three. And you'll notice that client number two is being lent book number five and that should not be allowed. And in fact, the foreign key constraint is designed to prevent this. So let's go ahead and we'll copy and paste this into our SQL box and.

I'm going to go ahead and I'm just going to press Go here. And you'll see that here's our client table, Freddy, Karen and Harry, one, two and three. Here's our books. These are actually books that I like. These are some of my favorite books. And here is the lend table. This is our junction table. And you notice that there's, all the time stamps are the same because we inserted all those rows at once. And we have client one borrowed two books, book number one and two. Client three borrowed book number three. And client two borrowed book number five, which does not exist.

And this is this joint query down here. Which you might use a query like this to look at your entire picture and you notice it uses left joins. We'll learn a little more about left joins in a later chapter, but all this is doing here is it's looking at the junction table and it's bringing in the names from the client and the book, tables. So we have the lend id, the lend stamp, the client name, and the book title and those are all joined together.

So you'll notice that here, Karen, that's client number two. Up here client number two is Karen. And she borrowed book number five which does not exist and so there's a NULL here and that's what it is that we want to prevent. And that actually happens here in this INSERT INTO lend. Right there in that query. INSERT INTO lend, VALUES two comma five. That's the one that should not be allowed. So let's go ahead and put our foreign key constraint in, and so we're going to do this in our lend table and we're going to come down here after the column, so I'll put in another comma, and I'm going to say.

Foreign key C-I-D, that's our client ID, references client ID, like that. And we'll just do another one and I'm going to copy and paste so that I don't have spelling problems. And this will be book ID, and it references book, ID. So the way this works, we have the foreign key keyword, and in parentheses is the column in the table that I'm using this in.

So c_ID, and what it references in the foreign table, foreign key, it's the foreign table, so client table because it's not this table. Is considered foreign. And, so the foreign table is the client table and its column is id that is being referenced here. So this foreign key for c_id REFERENCES the client table id and likewise for the book id and the book table. And I do not want that last comma there. That will give me a syntax error. And I'm going to press Go.

And now, we get integrity violation, cannot add or update a child row, a foreign key constraint fails. And it tells us which one here it is, lend b foreign key two. It's trying to tell us. It's a little bit cryptic here but it is the book id. That's not working. And of course, we know that, because if we come down here to our insert statement, we know that it's the book ID that's referencing this key 5 that doesn't exist. So now, when we look at our joined query, we have Freddy, Freddy, and Harry have all borrowed books.

And here, we actually don't have that fourth row with Karen borrowing a book that doesn't exist. And so this is exactly what we want to have happen. We want to have that insert to be not allowed because it's referring to a row that doesn't exist. So, that's Foreign Keys and that's how they work. It's a little bit. Complicated to demonstrate it because I need to have all of the structure in order to do that. I want to show you one other thing here. We're going to go ahead and take that one out so it doesn't generate that error anymore when I press go here so we don't get any errors.

But I do want to, after all of these rows are inserted here. Then we do the SELECT FROM lend. I want to come in here and try to delete a row that's being referenced, right? And so in the book table, id 2 is being referenced. That's because Harry has borrowed a book, Rendezvous with Rama, which is number 2. So, I want to come in here and I want to try and delete that row in the book table after its been referenced and you'll see that this is also disallowed.

So if I say DELETE FROM book WHERE id equals 2. And you'll see that that's not allowed. I get an integrity, violation cannot delete or update a parent row. Foreign key constraint fails. And that should be disallowed, because that would then make this table again, out of integrity. Because this row would now, again refer to. A book that doesn't exist. So this is important also when we try to drop these tables. Now that have these foreign key constraints in place.

When I try to drop these tables, I have to do them in a particular order. Actually I have them up here already. If I try to drop the client or book table before I drop the lend table. Sometimes, actually it doesn't happen all the time. But sometimes it'll give me that foreign key constraint. And it should. It should not allow that. So I have to drop the lend table first, then the client table, and then the book table. And that works and now all those tables are gone. And our database is back to its original state for the rest of the course.

So the foreign key constraint is an important feature for working with relational tables in MySQL. Keep in mind that most of the major databases have a foreign key constraint but the syntax differs significantly among the different database systems.

Show transcript

This video is part of

Image for MySQL Essential Training
MySQL Essential Training

60 video lessons · 6643 viewers

Bill Weinman
Author

 
Expand all | Collapse all
  1. 4m 22s
    1. Welcome
      1m 3s
    2. Using the exercise files
      1m 31s
    3. What is MySQL?
      1m 48s
  2. 45m 37s
    1. Installation overview
      3m 16s
    2. Installing XAMPP on Windows
      5m 55s
    3. Installing XAMPP on the Mac
      6m 38s
    4. Setting up MySQL users
      11m 31s
    5. Installing SID on Windows
      5m 43s
    6. Installing SID on the Mac
      6m 6s
    7. Installing time zone support in MySQL on Windows
      6m 28s
  3. 45m 43s
    1. The SELECT statement
      3m 57s
    2. Selecting rows
      4m 57s
    3. Selecting columns
      3m 8s
    4. Sorting results with ORDER BY
      2m 58s
    5. Filtering results with WHERE
      3m 52s
    6. Filtering results with LIKE and IN
      3m 41s
    7. Filtering results with regular expressions
      8m 21s
    8. Inserting rows
      4m 9s
    9. Updating rows
      2m 21s
    10. Deleting rows
      2m 25s
    11. Literal strings
      3m 12s
    12. Understanding NULL
      2m 42s
  4. 41m 47s
    1. Creating a database
      4m 30s
    2. Creating a table
      7m 18s
    3. Creating indexes
      6m 8s
    4. Controlling column behavior with constraints
      4m 46s
    5. Creating an ID column
      6m 58s
    6. Using foreign key constraints
      7m 58s
    7. Altering a table
      4m 9s
  5. 28m 56s
    1. What are data types?
      4m 1s
    2. Numeric types
      5m 21s
    3. String types
      2m 58s
    4. Date and time types
      7m 2s
    5. Bit type
      2m 26s
    6. Boolean values
      2m 15s
    7. Enumeration types
      4m 53s
  6. 32m 34s
    1. String functions
      6m 57s
    2. Numeric functions
      6m 2s
    3. Date and time functions
      4m 12s
    4. Time zones in MySQL
      3m 37s
    5. Formatting dates
      1m 51s
    6. Aggregate functions
      5m 45s
    7. Flow control with CASE
      4m 10s
  7. 7m 6s
    1. Maintaining database integrity with transactions
      4m 46s
    2. Using transactions for performance
      2m 20s
  8. 16m 49s
    1. Updating a table with a trigger
      5m 11s
    2. Preventing automatic updates with a trigger
      7m 29s
    3. Logging transactions with a trigger
      4m 9s
  9. 14m 11s
    1. Creating a simple subselect
      3m 23s
    2. Searching within a result set
      3m 53s
    3. Creating a view
      3m 32s
    4. Creating a joined view
      3m 23s
  10. 12m 26s
    1. Understanding MySQL stored routines
      2m 0s
    2. Creating a stored function
      4m 34s
    3. Creating a stored procedure
      5m 52s
  11. 14m 4s
    1. The multi-platform PDO interface
      3m 44s
    2. Executing the SQL
      4m 8s
    3. Implementing auto-increment IDs
      2m 3s
    4. Using a stored funciton
      4m 9s
  12. 1m 3s
    1. Goodbye
      1m 3s

Start learning today

Get unlimited access to all courses for just $25/month.

Become a member
Sometimes @lynda teaches me how to use a program and sometimes Lynda.com changes my life forever. @JosefShutter
@lynda lynda.com is an absolute life saver when it comes to learning todays software. Definitely recommend it! #higherlearning @Michael_Caraway
@lynda The best thing online! Your database of courses is great! To the mark and very helpful. Thanks! @ru22more
Got to create something yesterday I never thought I could do. #thanks @lynda @Ngventurella
I really do love @lynda as a learning platform. Never stop learning and developing, it’s probably our greatest gift as a species! @soundslikedavid
@lynda just subscribed to lynda.com all I can say its brilliant join now trust me @ButchSamurai
@lynda is an awesome resource. The membership is priceless if you take advantage of it. @diabetic_techie
One of the best decision I made this year. Buy a 1yr subscription to @lynda @cybercaptive
guys lynda.com (@lynda) is the best. So far I’ve learned Java, principles of OO programming, and now learning about MS project @lucasmitchell
Signed back up to @lynda dot com. I’ve missed it!! Proper geeking out right now! #timetolearn #geek @JayGodbold
Share a link to this course

What are exercise files?

Exercise files are the same files the author uses in the course. Save time by downloading the author's files instead of setting up your own files, and learn by following along with the instructor.

Can I take this course without the exercise files?

Yes! If you decide you would like the exercise files later, you can upgrade to a premium account any time.

Become a member Download sample files See plans and pricing

Please wait... please wait ...
Upgrade to get access to exercise files.

Exercise files video

How to use exercise files.

Learn by watching, listening, and doing, Exercise files are the same files the author uses in the course, so you can download them and follow along Premium memberships include access to all exercise files in the library.


Exercise files

Exercise files video

How to use exercise files.

For additional information on downloading and using exercise files, watch our instructional video or read the instructions in the FAQ.

This course includes free exercise files, so you can practice while you watch the course. To access all the exercise files in our library, become a Premium Member.

Are you sure you want to mark all the videos in this course as unwatched?

This will not affect your course history, your reports, or your certificates of completion for this course.


Mark all as unwatched Cancel

Congratulations

You have completed MySQL Essential Training.

Return to your organization's learning portal to continue training, or close this page.


OK
Become a member to add this course to a playlist

Join today and get unlimited access to the entire library of video courses—and create as many playlists as you like.

Get started

Already a member?

Become a member to like this course.

Join today and get unlimited access to the entire library of video courses.

Get started

Already a member?

Exercise files

Learn by watching, listening, and doing! Exercise files are the same files the author uses in the course, so you can download them and follow along. Exercise files are available with all Premium memberships. Learn more

Get started

Already a Premium member?

Exercise files video

How to use exercise files.

Ask a question

Thanks for contacting us.
You’ll hear from our Customer Service team within 24 hours.

Please enter the text shown below:

The classic layout automatically defaults to the latest Flash Player.

To choose a different player, hold the cursor over your name at the top right of any lynda.com page and choose Site preferencesfrom the dropdown menu.

Continue to classic layout Stay on new layout
Exercise files

Access exercise files from a button right under the course name.

Mark videos as unwatched

Remove icons showing you already watched videos if you want to start over.

Control your viewing experience

Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.

Interactive transcripts

Click on text in the transcript to jump to that spot in the video. As the video plays, the relevant spot in the transcript will be highlighted.

Are you sure you want to delete this note?

No

Your file was successfully uploaded.

Thanks for signing up.

We’ll send you a confirmation email shortly.


Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

Keep up with news, tips, and latest courses with emails from lynda.com.

Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

   
submit Lightbox submit clicked
Terms and conditions of use

We've updated our terms and conditions (now called terms of service).Go
Review and accept our updated terms of service.