Skip to content
Advertisement

Foreign Key Constraint Failed – Even when I try to manually add data

I am studying SQL in my data science degree program, and the assignment is to perform SQL queries for the first time. In order to do that, I have to paste the SQL starter code in and run it. However, when I do, I hit an error that I can’t solve. My class is online and my professor hasn’t responded and, since this isn’t part of the graded part of the assignment, I figured I’d try here to get help on this error.

Edit: It was pointed out that I didn’t include all of the tables. Please see full code for all tables and all data. I was trying to avoid flooding this post with a lot of lines of code, but it seems I left out pertinent information. See below.

The tables were created with these blocks of code:

Then, I added data to instructor and section with the follow. Side note, I had to go in and manually set the time_slot_id as a primary key to avoid getting an error.

I didn’t have a problem. Finally, I tried to run this:

The error occurred on the last line. I always get:

Result: FOREIGN KEY constraint failed
At line 1: (Note: I tried re-running it by itself afterwards, thus the “Line 1”)
INSERT INTO teaches VALUES (‘44444’, ‘MAT-114’, ‘2’, ‘Fall’, 2019);

I checked over each constraint, looked at each column, and couldn’t figure it out. I even went in and entered the data manually in the “Browse Data” tab within DB Browser Lite; while I was able to enter the first 4 values, when I try to enter anything for year, I get the same error in a popup box. Even when I click in the box, leave it blank, then try to click out, I get the same error. See image.

Please assist… I’m lost at this point and quite frustrated.

Error Message

Advertisement

Answer

There are two things here:

  1. the issue, and
  2. how to work out what the issue is.

Let’s start with 2).

The error message is:

Result: FOREIGN KEY constraint failed
At line 1:
INSERT INTO teaches VALUES (‘44444’, ‘MAT-114’, ‘2’, ‘Fall’, 2019);

That tells us to look at the foreign keys defined on the teaches table.

There are 2:

  • ID references the ID in instructor table (aside: maybe call this instructor_id instead of ID, it’ll make more sense in 6 weeks when you come back to look at it).
  • course_id, sec_id, semester, year reference the section table.

There is, in your data, an instructor with ID ‘44444’, so that’s probably not the problem.

But it doesn’t look like there’s a row in section with 'MAT-114', '2', 'Fall', 2019 and that is likely your problem.

Note also that there’s not one for ‘MTH-114’ like in the image, either.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement