SQL foreign key order of execution constraints - mysql

Is order of execution important when creating Primary/Foreign Key links in a MySQL statement?
For example, the following code will produce the error: "Cannot add foreign key constraint"
CREATE TABLE IF NOT EXISTS Movies
(
MovieID INT NOT NULL AUTO_INCREMENT,
GenreID INT NOT NULL,
PRIMARY KEY(MovieID),
FOREIGN KEY(GenreID) References Genres(GenreID)
);
CREATE TABLE IF NOT EXISTS Genres
(
GenreID INT NOT NULL AUTO_INCREMENT,
GenreName VARCHAR(30),
Primary key (GenreID)
);
Cannot add foreign key constraint
But when the Genre table is created FIRST, the error no longer persists:
CREATE TABLE IF NOT EXISTS Genres
(
GenreID INT NOT NULL AUTO_INCREMENT,
GenreName VARCHAR(30),
Primary key (GenreID)
);
CREATE TABLE Movies
(
MovieID INT NOT NULL AUTO_INCREMENT,
GenreID INT NOT NULL,
PRIMARY KEY(MovieID),
FOREIGN KEY(GenreID) References Genres(GenreID)
);
Schema Ready
Is the error caused because the table hasn't been created yet, so it doesn't know where / what the Genre tables PK type is?
When I was searching for a solution to foreign key constraints all I found was information on the data type matching, but not the order of execution. Thanks.

Is the error caused because the table hasn't been created yet, so it doesn't know where / what the Genre tables PK type is?
Yes.
If you define the Movies table first, MySQL is going to try to find the referenced Genres table, which does not yet exist. So you should create them in the opposite order:
CREATE TABLE IF NOT EXISTS Genres
CREATE TABLE IF NOT EXISTS Movies

Foreign key is a reference to another key: primary key. If primary key doesn't exist now, you can not reference to an unknown thing, so you get exception.

Related

mysql error 1822 when trying to create new table with a FOREIGN KEY

trying the following code:
create table donation(
donation_number int not null primary key ,
product_id int not null
);
create table stock (
product_id int not null primary key,
available_qty int not null,
FOREIGN KEY (product_id ) REFERENCES donation(product_id)
);
Give back
Error Code: 1822. Failed to add the foreign key constraint. Missing index for constraint 'stock_ibfk_1' in the referenced table 'donation'.
Why? how can I solve this problem?
to create a foreign key relationship, the parent table column on which you are creating relation must be unique or primary and they must have the same datatype and size also
product_id in donation table is not unique.

MySQL - How to create a foreign key between three tables

I have been set the task of creating 3 tables in MySql. One table called subjects with a field called subject_id as the primary key, another table called students with a field called student_id and a final table called entries.
The entries table must have two foreign keys, subject_id and student_id.
This is the official task:
Can anyone possibly help?
In your create table query after you define the column that will be your foreign key, simply write "Foreign Key - References -" and specify the column (where I wrote the first dash mark) you wish to connect to the other table. The second dash should be the table name followed by the column it references in parentheses.
If the table is already made, just use an alter table query and write "add foreign key - references -" with the same format as above.
Something like this
CREATE TABLE Subjects (
SubjectId INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY (SubjectId))
CREATE TABLE Students (
StudentId INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY (StudentId))
CREATE TABLE Entries(
EntriesId INT NOT NULL AUTO_INCREMENT,
SubjectId INT NOT NULL,
StudentId INT NOT NULL,
FOREIGN KEY (SubjectId) REFERENCES Subjects (SubjectId),
FOREIGN KEY (StudentId) REFERENCES Students (StudentId))

How to add foreign key to table in mysql

What I am doing incorrect? Trying to create these tables in sqlfiddle
does not work gives
Cannot add foreign key constraint
create table product (
pid int NOT NULL,
name varchar(10),
PRIMARY KEY (pid)
);
create table trans (
tid int NOT NULL ,
productId int NOT NULL,
userId int NOT NULL,
PRIMARY KEY (tid),
FOREIGN KEY (productId) REFERENCES product(pid),
FOREIGN KEY (userId) REFERENCES user1(uid)
);
create table user1 (
uid int NOT NULL ,
location varchar(22),
PRIMARY KEY (uid)
);
As #BillKarwin mentioned, the definitions for tables containing primary keys referenced by the trans table should appear before the definition for the trans table. So you should move the definition for the trans table to last.
However, even doing this still results in an error in SQLFiddle:
SQLFiddle (uncomment the foreign key reference in trans)
SQLFiddle seems to have some sort of problem with accepting this table schema. This is not surprising, as the site seems to have such problems frequently.
What is order you create tables. You need first to create product and user1 and at the end - trans.

Altering MySQL table to add foreign key constraint leads to errors

Question:
Why am I getting errors when trying to alter a table with a foreign key constraint?
Details:
I have 1 table, HSTORY which I use as a base table for all other specific history tables (ie. USER_HISTORY, BROWSER_HISTORY, PICTURE_HISTORY...). I have also included the PICTURE and USER tables as they get called as well.
HISTORY table:
CREATE TABLE IF NOT EXISTS HISTORY
(
ID INT NOT NULL AUTO_INCREMENT,
VIEWERID INT NOT NULL ,
VIEWDATE TIMESTAMP NOT NULL DEFAULT NOW(),
PRIMARY KEY (ID),
FOREIGN KEY (VIEWERID) REFERENCES USER(ID)
)
engine=innodb;
USER table: (in case anyone is curious)
CREATE TABLE IF NOT EXISTS USER
(
ID INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY (ID)
)
engine=innodb;
PICTURE table: (in case anyone is curious)
CREATE TABLE IF NOT EXISTS PICTURE
(
ID INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY (ID)
)
engine=innodb;
PICTURE_HISTORY table:
CREATE TABLE IF NOT EXISTS PICTURE_HISTORY LIKE HISTORY;
ALTER TABLE PICTURE_HISTORY
ADD FOREIGN KEY (FOREIGNID) REFERENCES PICTURE(ID);
However, when I do this, I get:
Key column 'FOREIGNID' doesn't exist in table
I take this to mean that I have to first create FOREIGNID, but in many of the examples on SO, the above should work. Anyone know why this is occurring?
Thanks to Michael for pointing out my mistake. I can't actually make a foreign key unless the column already exists. If instead I issue these two commands, the foreign key constraint is created:
ALTER TABLE PICTURE_HISTORY
ADD COLUMN FOREIGNID INT NOT NULL;
ALTER TABLE PICTURE_HISTORY
ADD FOREIGN KEY (FOREIGNID) REFERENCES PICTURE(ID);
You can combine commands for mysql using a comma, like so:
ALTER TABLE PICTURE_HISTORY
ADD COLUMN FOREIGNID INT NOT NULL,
ADD FOREIGN KEY (FOREIGNID) REFERENCES PICTURE(ID);

Self relationship in MySQL

I am trying to add a self relation in an existing Innodb table here is table structure
Table person
person_id int (10) primary key not null auto increment,
parent_id int (10) NULL default null,
name varchar(30)
When I use this command
ALTER TABLE `person` ADD FOREIGN KEY ( `parent_id` ) REFERENCES `person` (`person_id`) ON DELETE RESTRICT ON UPDATE RESTRICT ;
I get the error data type mismatch. I think this could be due to null values in parent_id. Is there any way to skip this check?
Thanks
person_id and parent_id need to be the exact same data type. For example, if person_id is INT UNSIGNED and parent_id is INT, then you can't create the foreign key.
Run this command and compare the data types of the two columns:
SHOW CREATE TABLE `person`\G