Search code examples
mysqlforeign-keysmariadbcreate-table

MariaDB "Foreign key constraint is incorrectly formed" error


Browsed through other similar questions have not helped, I'm creating two simple tables and this error pops up, have no idea where it's gone wrong:

create table department (
    dept_name varchar(20),  
    building varchar(15),  
    budget numeric(12,2),  
    primary key (dept_name)
) COLLATE='utf8_general_ci' ENGINE=INNODB;

Now when I create second table:

create table course (
    course_id varchar(7), 
    title varchar(50), 
    dept_name varchar(20), 
    credits numeric(2,0), 
    primary key (course_id), 
    foreign key (dept_name) references department
) COLLATE='utf8_general_ci' ENGINE=INNODB;

It gives me the error. What am I missing here?


Solution

  • The foreign key syntax is:

    foreign key (dept_name) references department(dept_name)
                           --  column name here --^