FOREIGN KEY
FOREIGN KEY
constraint protects data integrity. Let's create
students
and
note
tables
USE university;
DROP TABLE IF EXISTS students;
CREATE TABLE students (
    id int AUTO_INCREMENT,
    first_name varchar(50),
    last_name varchar(50),
    PRIMARY KEY(id)
);
Let's add
FOREIGN KEY
called
fk_student_note
to the
notes
table
DROP TABLE IF EXISTS notes;
CREATE TABLE notes (
    id int AUTO_INCREMENT,
    student_id int,
    title varchar(50),
    description varchar(50),
    PRIMARY KEY(id),
    INDEX(student_id),
    CONSTRAINT fk_student_note  
        FOREIGN KEY (student_id)  
        REFERENCES students(id) 
        ON UPDATE CASCADE 
        ON DELETE RESTRICT
);
by Valeri Tandilashvili
4 years ago
MySQL
1
Pro tip: use ```triple backticks around text``` to write in code fences