Как изменить foreign key mysql

Создаем внешний и первичный ключи таблиц MySQL. Расскажем, как использовать первичный, внешний и вторичный ключ, создание в СУБД MySQL с помощью CREATE TABLE books и ALTER TABLE и удаление ключей

Введение 

Работа современных приложений и сложных сайтов, которыми мы привыкли пользоваться, невозможна без баз данных. Поэтому правильно настроенные БД важны для приложения не меньше, чем их дизайн и код, который с этой базой взаимодействует. Работа современных реляционных баз данных сложно представить без корректно настроенных первичных и внешних ключей. В этой инструкции мы подробно разберем создание этих ключей MySQL, расскажем для чего они нужны и как их использовать.

Облачные базы данных

Подробнее

Что такое первичный и внешний ключи и зачем они нужны

Начнем рассмотрение данного вопроса с двух самых главных элементов: первичного и внешнего ключей.

Первичный ключ или primary key

Первичный ключ — особенное поле в SQL-таблице, которое позволяет однозначно идентифицировать каждую запись в ней. Как правило, эти поля используются для хранения уникальных идентификаторов объектов, которые перечислены в таблице, например, это может быть ID клиента или товара.
Первичный ключ имеет несколько свойств:

  • каждая запись в таком поле должна быть уникальной;
  • запись в поле не должна быть пустой;
  • в одной таблице может быть только один ключ (существуют также составные ключи, которые могут включать в себя несколько полей, однако в этой статье мы не будем их рассматривать).

Внешний ключ или foreign key

Внешний ключ нужен для того, чтобы связать две разные SQL-таблицы между собой. Внешний ключ таблицы должен соответствует значению первичного ключа таблицы, с которой он связан. Это помогает сохранять согласованность базы данных путем обеспечения так называемой «ссылочной целостности» (referential integrity).

Давайте рассмотрим все это на примере простой базы данных. Для начала нам понадобится создать базу данных. Заходим в MySQL и создаем базу данных, в которой будут храниться записи о книгах в библиотеке:

    create database slcbookshelf;

пример БД

Так как дальше мы будем работать с этой базой, вводим команду:

    use slcbookshelf;

И создаем таблицу, в которой будут храниться записи о книгах в библиотеке:

    CREATE TABLE books (
book_id INT NOT NULL,
book_name VARCHAR(255) NOT NULL,
book_category VARCHAR(255));

В созданной выше таблице ни одно из полей не является первичным ключом. Увидеть это мы можем, выполнив команду:

    DESC books;

Вывод команды будет выглядеть следующим образом:

    mysql> DESC books;
+---------------+--------------+------+-----+---------+-------+
| Field     	| Type     	| Null | Key | Default | Extra |
+---------------+--------------+------+-----+---------+-------+
| book_id   	| int      	| NO   | 	| NULL	|   	|
| book_name 	| varchar(255) | NO   | 	| NULL	|   	|
| book_category | varchar(255) | YES  | 	| NULL	|   	|
+---------------+--------------+------+-----+---------+-------+
3 rows in set (0.00 sec)

Первичный ключ при создании таблицы

Вы можете также создать его при создании таблицы, добавив в команду для создания таблицы следующую запись:

    PRIMARY KEY (book_id)

В таком случае поле book_id после создания таблицы будет являться первичным ключом для таблицы books.

Создание первичного ключа при помощи ALTER TABLE

Если таблица уже создана, а первичный ключ в ней не указан, вы можете создать ключевое поле, с помощью команды ALTER TABLE. Команда ALTER TABLE помогает изменять уже существующие столбцы, удалять их или добавлять новые. Чтобы определить первичный ключ в поле book_id, выполните команду:

    ALTER TABLE books
ADD PRIMARY KEY (book_id);

Проверяем:
mysql> DESC books;
+---------------+--------------+------+-----+---------+-------+
| Field     	| Type     	| Null | Key | Default | Extra |
+---------------+--------------+------+-----+---------+-------+
| book_id   	| int      	| NO   | PRI | NULL	|   	|
| book_name 	| varchar(255) | NO   | 	| NULL	|   	|
| book_category | varchar(255) | YES  | 	| NULL	|   	|
+---------------+--------------+------+-----+---------+-------+
3 rows in set (0.00 sec)

Установка внешнего ключа MySQL при создании таблицы и с помощью ALTER TABLE

Предположим, у нас есть еще одна таблица под названием authors, которую нам необходимо связать с текущей таблицей books с помощью внешнего ключа author_id.

Внешний ключ при создании таблицы

Для того, чтобы привязать к таблице внешний ключ сразу при создании таблицы, вам необходимо дополнить запрос, которым вы создаете таблицу следующей записью:

    FOREIGN KEY (author_id) REFERENCES authors(author_id)


В итоге запрос, которым создается такая таблица будет выглядеть следующим образом:

    CREATE TABLE books (
book_id INT NOT NULL,
book_name VARCHAR(255) NOT NULL,
book_category VARCHAR(255),
FOREIGN KEY (author_id) REFERENCES authors(author_id));

Создание внешнего ключа при помощи ALTER TABLE

Если вам нужно определить поле уже созданной таблицы в качестве внешнего ключа, вы можете воспользоваться командой ALTER TABLE и создать внешний ключ в таблице командой:

    ALTER TABLE books ADD FOREIGN KEY (author_id) REFERENCES authors(author_id);

Сценарии использования внешнего ключа

Внешний ключ является очень важным и мощным инструментом в работе современных баз данных. С помощью внешнего ключа, например, вы можете настроить параметры, которые зададут действия при удалении или обновлении строки в таблице, настроить каскадное удаление или запретить изменять строку в таблице. Давайте рассмотрим на примерах.

Каскадное удаление или CASCADE

Каскадное удаление позволит вам одновременно удалить строки из главной таблицы, а вместе с ними удалить все связанные строки в других таблицах. Задается каскадное удаление таким запросом:

    CREATE TABLE Orders(
Id INT PRIMARY KEY AUTO_INCREMENT,
CustomerId INT,
CreatedAt Date,
FOREIGN KEY (CustomerId) REFERENCES Customers (Id) ON DELETE CASCADE);


Аналогично работает метод ON UPDATE CASCADE. При попытке изменить значение, записанное в поле первичного ключа, изменение будет применено к внешнему ключу, связанному с данным полем. Этот метод используется крайне редко, так как первичные ключи практически не являются изменяемыми полями.

RESTRICT

Опция RESTRICT позволяет отклонять все запросы на изменение или удаление строк в главной таблице при условии, что в связанной таблице также имеются строки. Задается данное ограничение следующим запросом:

    CREATE TABLE Orders(
Id INT PRIMARY KEY AUTO_INCREMENT,
Customer_Id INT,
CreatedAt Date,
FOREIGN KEY (Customer_Id) REFERENCES Customers (Id) ON DELETE RESTRICT);

Заключение

В данной статье мы рассмотрели что такое первичный и внешний ключи SQL, зачем они нужны и как их создать различными способами: при создании таблицы или при помощи ALTER TABLE. Также мы рассмотрели несколько сценариев использования внешнего ключа для управления таблицами.

In this article, we will discuss the overview of foreign keys and will discuss how to add a foreign key using ALTER in MySQL step by step. Let’s discuss it one by one.

Foreign key
If an attribute is a primary key in one table but was not used as a primary key in another table then the attribute which is not a primary key in the other table is called a foreign key. If the changes made or any data is manipulated in any of the tables the changes get reflected in both the tables with the help of foreign key constraint.

Steps to add a foreign key using ALTER in MySQL :
Here let us see how to add an attribute of student which is the primary key in the student table as a foreign key in another table exam as follows.

Step-1: Creating a database university :
Here, you will see how to create a database in MySQL as follows.

CREATE DATABASE university;

Output :

Step-2: Using the database university :
Here, you will see how you can use the existing database which you have already created as follows.

USE university;

Output :

Step-3: Creating a table student :
Here, you will see how to create a table in MySQL as follows.

 CREATE TABLE student
 (
     student_id INT PRIMARY KEY,
     student_name varchar,
     student_branch varchar
 );

Output :

Step-4: Viewing the description of the table :
Here, you will see how to verify the table as follows.

DESCRIBE student;

Output :
Here, as you can see in the description the key column of student_id is PRI which means it is the primary key in that table student.

Field Type Null Key Default Extra
student_id int  NO PRI NULL  
student_name varchar(20) YES   NULL  
student_branch varchar(20) YES   NULL  

Step-5: Creating another table exam :
In this step, you will see one more table for reference.

CREATE TABLE exam
 (
    exam_id INT PRIMARY KEY,
    exam_name varchar(20)
 );

Output :

Step-6: Viewing the description of the table :
In this step, you can verify the table you have created.

DESCRIBE exam;

Output :

Field Type Null Key Default Extra
exam_id int  NO PRI NULL  
exam_name varchar(20) YES   NULL  

Step-7: Adding another column student_id into the exam table :
Here, you will see how to add another column student_id into the exam table as follows.

 ALTER TABLE exam
 ADD COLUMN student_id INT;

Output :

Step-8: Making a foreign key :
Here, you will see how to make the student_id attribute foreign key in the exam table which is the primary key in the student table as follows.

Syntax –

ALTER TABLE table_name
ADD FOREIGN KEY (column_name)
REFERENCE table_name(Referencing column_name in table_name);

Query –

ALTER TABLE exam
ADD FOREIGN KEY(student_id)
REFERENCES student(student_id);

Output :

Step-9: Verifying the exam table : 
Here, you will see the description of the exam table as follows. 

DESCRIBE exam;

Output :
Now as you can see in the description of the table exam one more column student_id is added and in the Key column of description, the student_id has MUL which means it is a foreign key.

Field Type Null Key Default Extra
exam_id int  NO PRI NULL  
exam_name varchar(20) YES   NULL  
student_id int YES MUL NULL  

In this article, we will discuss the overview of foreign keys and will discuss how to add a foreign key using ALTER in MySQL step by step. Let’s discuss it one by one.

Foreign key
If an attribute is a primary key in one table but was not used as a primary key in another table then the attribute which is not a primary key in the other table is called a foreign key. If the changes made or any data is manipulated in any of the tables the changes get reflected in both the tables with the help of foreign key constraint.

Steps to add a foreign key using ALTER in MySQL :
Here let us see how to add an attribute of student which is the primary key in the student table as a foreign key in another table exam as follows.

Step-1: Creating a database university :
Here, you will see how to create a database in MySQL as follows.

CREATE DATABASE university;

Output :

Step-2: Using the database university :
Here, you will see how you can use the existing database which you have already created as follows.

USE university;

Output :

Step-3: Creating a table student :
Here, you will see how to create a table in MySQL as follows.

 CREATE TABLE student
 (
     student_id INT PRIMARY KEY,
     student_name varchar,
     student_branch varchar
 );

Output :

Step-4: Viewing the description of the table :
Here, you will see how to verify the table as follows.

DESCRIBE student;

Output :
Here, as you can see in the description the key column of student_id is PRI which means it is the primary key in that table student.

Field Type Null Key Default Extra
student_id int  NO PRI NULL  
student_name varchar(20) YES   NULL  
student_branch varchar(20) YES   NULL  

Step-5: Creating another table exam :
In this step, you will see one more table for reference.

CREATE TABLE exam
 (
    exam_id INT PRIMARY KEY,
    exam_name varchar(20)
 );

Output :

Step-6: Viewing the description of the table :
In this step, you can verify the table you have created.

DESCRIBE exam;

Output :

Field Type Null Key Default Extra
exam_id int  NO PRI NULL  
exam_name varchar(20) YES   NULL  

Step-7: Adding another column student_id into the exam table :
Here, you will see how to add another column student_id into the exam table as follows.

 ALTER TABLE exam
 ADD COLUMN student_id INT;

Output :

Step-8: Making a foreign key :
Here, you will see how to make the student_id attribute foreign key in the exam table which is the primary key in the student table as follows.

Syntax –

ALTER TABLE table_name
ADD FOREIGN KEY (column_name)
REFERENCE table_name(Referencing column_name in table_name);

Query –

ALTER TABLE exam
ADD FOREIGN KEY(student_id)
REFERENCES student(student_id);

Output :

Step-9: Verifying the exam table : 
Here, you will see the description of the exam table as follows. 

DESCRIBE exam;

Output :
Now as you can see in the description of the table exam one more column student_id is added and in the Key column of description, the student_id has MUL which means it is a foreign key.

Field Type Null Key Default Extra
exam_id int  NO PRI NULL  
exam_name varchar(20) YES   NULL  
student_id int YES MUL NULL  

Adam McGurk

Adam McGurk

Posted on May 18, 2020

• Updated on May 19, 2020

Alter a foreign key constraint in MySQL

(PS…if you want to skip to just the answer Click this link)

I ran into a problem today.

I found a foreign key in my table that cascaded instead of set the key as null.

As you can imagine, this was not a great thing to learn. I lost quite a few log records. Luckily, this is an application used only by me, and I had backups that I could restore to that lost very little data. But finding how to reverse this foreign key effect proved challenging.

When I went to Google for my answer, I found it challenging. There isn’t much information about how to alter foreign keys in MySQL.

There is no command like:

ALTER TABLE my_table CHANGE FOREIGN KEY (key_name) REFERENCES other_table(other_key) ON DELETE SET NULL;

Enter fullscreen mode

Exit fullscreen mode

That would be sublime if that existed!! Alas, it doesn’t, so we must find a workaround. Here is what the workaround looks like.

First — Get the name of your foreign key constraint.

If you’re like me, you create your tables (and constraints) like this:

CREATE TABLE my_table (
    name varchar(255),
    key int(11),
    FOREIGN KEY key REFERENCES other_table(id) ON DELETE SET NULL
);

Enter fullscreen mode

Exit fullscreen mode

or like this

ALTER TABLE my_table ADD FOREIGN KEY (key) REFERENCES other_table(id) ON DELETE CASCADE;

Enter fullscreen mode

Exit fullscreen mode

Without the full MySQL name of the constraint. So how do we get the name that MySQL needs to drop the constraint?

Enter the SHOW CREATE TABLE command.

The output of this command contains the name of the constraint that you need. Here is what that output would look like for my above CREATE TABLE (or ALTER TABLE) command:

SHOW CREATE TABLE my_tableG

Enter fullscreen mode

Exit fullscreen mode

*************************** 1. row ***************************
       Table: my_table
Create Table: CREATE TABLE `my_table` (
  `name` varchar(255) DEFAULT NULL,
  `key` int(11) DEFAULT NULL,
  KEY `ke` (`key`),
  CONSTRAINT `my_table_ibfk_1` FOREIGN KEY (`key`)
  REFERENCES `other_table` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4

Enter fullscreen mode

Exit fullscreen mode

So the name of our foreign key constraint would be «my_table_ibfk_1»;

Second — Drop the foreign key constraint.

Now that we have the name to our foreign key constraint, we need to drop it. And this is the part that held me up the most.

I didn’t know the consequences to dropping a foreign key constraint. I was afraid because of my own ignorance.

Turns out, there was nothing to be afraid of. If you drop the foreign key constraint, it doesn’t have any other effects, and keeps all values intact.

So, here’s the code to run to do that:

ALTER TABLE my_table DROP FOREIGN KEY my_table_ibfk_1;

Enter fullscreen mode

Exit fullscreen mode

Third — Create your new foreign key constraint

In my case, we need to change the cascade to a set null command. Here is how you would do that:

ALTER TABLE my_table ADD FOREIGN KEY (key) REFERENCES other_table(id) ON DELETE SET NULL;

Enter fullscreen mode

Exit fullscreen mode

And that’s it!! That’s how you change a foreign key constraint in MySQL!

TL;DR

  1. Get the name of your foreign key constraint:
    If you don’t know the name, run this command:

    SHOW CREATE TABLE your_table_name_hereG
    

    And you will get an output that looks something like this:

    *************************** 1. row ***************************
           Table: your_table_name_here
    Create Table: CREATE TABLE `your_table_name_here` (
      `id` int DEFAULT NULL,
      `parent_id` int DEFAULT NULL,
      KEY `par_ind` (`parent_id`),
      CONSTRAINT `name_of_your_constraint` FOREIGN KEY (`parent_id`)
      REFERENCES `parent` (`id`) ON DELETE CASCADE
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
    

    Which is where the name of your constraint will be (After the keyword «Constraint». There may be several, but you should be able to pick yours out).

  2. Drop your foreign key constraint:

    ALTER TABLE your_table_name_here DROP FOREIGN KEY name_of_your_constraint;
    
  3. Create your new foreign key constraint:

    ALTER TABLE your_table_name_here ADD FOREIGN KEY (parent_id) REFERENCES parent(id) ON DELETE SET NULL;
    

And that’s it! That’s how you change your foreign key constraint in MySQL

An Animated Guide to Node.js Event Lop

Node.js doesn’t stop from running other operations because of Libuv, a C++ library responsible for the event loop and asynchronously handling tasks such as network requests, DNS resolution, file system operations, data encryption, etc.

What happens under the hood when Node.js works on tasks such as database queries? We will explore it by following this piece of code step by step.

Read next


viniciusenari profile image

Automating Content Creation with Python: Obtaining Clips from Twitch

Vinicius Koji Enari — Jan 25


ycrydev profile image

How to get Wallet Addresses from Comment section of a Tweet

Ycrypto-3 — Jan 2


polterguy profile image

Include ChatGPT on your WordPress website

Thomas Hansen — Jan 25


codenameone profile image

Memory Debugging — a Deep Level of Insight

Shai Almog — Jan 24

Once unpublished, all posts by mcgurkadam will become hidden and only accessible to themselves.

If mcgurkadam is not suspended, they can still re-publish their posts from their dashboard.

Note:

Once unpublished, this post will become invisible to the public and only accessible to Adam McGurk.

They can still re-publish the post if they are not suspended.

Thanks for keeping DEV Community 👩‍💻👨‍💻 safe. Here is what you can do to flag mcgurkadam:

Make all posts by mcgurkadam less visible

mcgurkadam consistently posts content that violates DEV Community 👩‍💻👨‍💻’s
code of conduct because it is harassing, offensive or spammy.

Последнее обновление: 27.04.2019

Внешние ключи позволяют установить связи между таблицами. Внешний ключ устанавливается для столбцов из зависимой, подчиненной таблицы, и
указывает на один из столбцов из главной таблицы. Как правило, внешний ключ указывает на первичный ключ из связанной главной таблицы.

Общий синтаксис установки внешнего ключа на уровне таблицы:

[CONSTRAINT имя_ограничения]
FOREIGN KEY (столбец1, столбец2, ... столбецN) 
REFERENCES главная_таблица (столбец_главной_таблицы1, столбец_главной_таблицы2, ... столбец_главной_таблицыN)
[ON DELETE действие]
[ON UPDATE действие]

Для создания ограничения внешнего ключа после FOREIGN KEY указывается столбец таблицы, который будет представляет
внешний ключ. А после ключевого слова REFERENCES указывается имя
связанной таблицы, а затем в скобках имя связанного столбца, на который будет указывать внешний ключ. После выражения REFERENCES
идут выражения ON DELETE и ON UPDATE, которые задают действие при удалении и обновлении строки из
главной таблицы соответственно.

Например, определим две таблицы и свяжем их посредством внешнего ключа:

CREATE TABLE Customers
(
    Id INT PRIMARY KEY AUTO_INCREMENT,
    Age INT, 
    FirstName VARCHAR(20) NOT NULL,
    LastName VARCHAR(20) NOT NULL,
    Phone VARCHAR(20) NOT NULL UNIQUE
);

CREATE TABLE Orders
(
    Id INT PRIMARY KEY AUTO_INCREMENT,
    CustomerId INT,
    CreatedAt Date,
    FOREIGN KEY (CustomerId)  REFERENCES Customers (Id)
);

В данном случае определены таблицы Customers и Orders. Customers является главной и представляет клиента. Orders является зависимой и
представляет заказ, сделанный клиентом. Таблица Orders через столбец CustomerId связана с таблицей Customers и ее столбцом Id. То есть столбец
CustomerId является внешним ключом, который указывает на столбец Id из таблицы Customers.

С помощью оператора CONSTRAINT можно задать имя для ограничения внешнего ключа:

CREATE TABLE Orders
(
    Id INT PRIMARY KEY AUTO_INCREMENT,
    CustomerId INT,
    CreatedAt Date,
    CONSTRAINT orders_custonmers_fk 
    FOREIGN KEY (CustomerId)  REFERENCES Customers (Id)
);

ON DELETE и ON UPDATE

С помощью выражений ON DELETE и ON UPDATE можно установить действия, которые выполняются
соответственно при удалении и изменении связанной строки из главной таблицы. В качестве действия могут использоваться следующие опции:

  • CASCADE: автоматически удаляет или изменяет строки из зависимой таблицы при удалении или изменении связанных строк в главной таблице.

  • SET NULL: при удалении или обновлении связанной строки из главной таблицы устанавливает для столбца внешнего ключа
    значение NULL. (В этом случае столбец внешнего ключа должен поддерживать установку NULL)

  • RESTRICT: отклоняет удаление или изменение строк в главной таблице при наличии связанных строк в зависимой таблице.

  • NO ACTION: то же самое, что и RESTRICT.

  • SET DEFAULT: при удалении связанной строки из главной таблицы устанавливает для столбца внешнего ключа значение по
    умолчанию, которое задается с помощью атрибуты DEFAULT. Несмотря на то, что данная опция в принципе доступна, однако движок InnoDB не поддерживает данное выражение.

Каскадное удаление

Каскадное удаление позволяет при удалении строки из главной таблицы автоматически удалить все связанные строки из зависимой таблицы.
Для этого применяется опция CASCADE:

CREATE TABLE Orders
(
    Id INT PRIMARY KEY AUTO_INCREMENT,
    CustomerId INT,
    CreatedAt Date,
    FOREIGN KEY (CustomerId) REFERENCES Customers (Id) ON DELETE CASCADE
);

Подобным образом работает и выражение ON UPDATE CASCADE. При изменении значения первичного ключа автоматически изменится
значение связанного с ним внешнего ключа. Однако поскольку первичные ключи изменяются очень редко, да и с принципе не рекомендуется использовать в
качестве первичных ключей столбцы с изменяемыми значениями, то на практике выражение ON UPDATE используется редко.

Установка NULL

При установки для внешнего ключа опции SET NULL необходимо, чтобы столбец внешнего ключа допускал значение NULL:

CREATE TABLE Orders
(
    Id INT PRIMARY KEY AUTO_INCREMENT,
    CustomerId INT,
    CreatedAt Date,
    FOREIGN KEY (CustomerId) REFERENCES Customers (Id) ON DELETE SET NULL
);

Summary: in this tutorial, you will learn about MySQL foreign key and how to create, drop, and disable a foreign key constraint.

Introduction to MySQL foreign key

A foreign key is a column or group of columns in a table that links to a column or group of columns in another table. The foreign key places constraints on data in the related tables, which allows MySQL to maintain referential integrity.

Let’s take a look at the following customers and orders tables from the sample database.

In this diagram, each customer can have zero or many orders and each order belongs to one customer.

The relationship between customers table and orders table is one-to-many. And this relationship is established by the foreign key in the orders table specified by the customerNumber column.

The customerNumber column in the orders table links to the customerNumber primary key column in the customers table.

The customers table is called the parent table or referenced table, and the orders table is known as the child table or referencing table.

Typically, the foreign key columns of the child table often refer to the primary key columns of the parent table.

A table can have more than one foreign key where each foreign key references to a primary key of the different parent tables.

Once a foreign key constraint is in place, the foreign key columns from the child table must have the corresponding row in the parent key columns of the parent table or values in these foreign key column must be NULL (see the SET NULL action example below).

For example, each row in the orders table has a customerNumber that exists in the customerNumber column of the customers table. Multiple rows in the orders table can have the same customerNumber.

Self-referencing foreign key

Sometimes, the child and parent tables may refer to the same table. In this case, the foreign key references back to the primary key within the same table.

See the following employees table from the sample database.

The reportTo column is a foreign key that refers to the employeeNumber column which is the primary key of the employees table.

This relationship allows the employees table to store the reporting structure between employees and managers. Each employee reports to zero or one employee and an employee can have zero or many subordinates.

The foreign key on the column reportTo is known as a recursive or self-referencing foreign key.

MySQL FOREIGN KEY syntax

Here is the basic syntax of defining a foreign key constraint in the CREATE TABLE or ALTER TABLE statement:

[CONSTRAINT constraint_name] FOREIGN KEY [foreign_key_name] (column_name, ...) REFERENCES parent_table(colunm_name,...) [ON DELETE reference_option] [ON UPDATE reference_option]

Code language: SQL (Structured Query Language) (sql)

In this syntax:

First, specify the name of foreign key constraint that you want to create after the CONSTRAINT keyword. If you omit the constraint name, MySQL automatically generates a name for the foreign key constraint.

Second, specify a list of comma-separated foreign key columns after the FOREIGN KEY keywords. The foreign key name is also optional and is generated automatically if you skip it.

Third, specify the parent table followed by a list of comma-separated columns to which the foreign key columns reference.

Finally, specify how foreign key maintains the referential integrity between the child and parent tables by using the ON DELETE and ON UPDATE clauses.  The reference_option determines action which MySQL will take when values in the parent key columns are deleted (ON DELETE) or updated (ON UPDATE).

MySQL has five reference options: CASCADE, SET NULL, NO ACTION, RESTRICT, and SET DEFAULT.

  • CASCADE: if a row from the parent table is deleted or updated, the values of the matching rows in the child table automatically deleted or updated.
  • SET NULL:  if a row from the parent table is deleted or updated, the values of the foreign key column (or columns) in the child table are set to NULL.
  • RESTRICT:  if a row from the parent table has a matching row in the child table, MySQL rejects deleting or updating rows in the parent table.
  • NO ACTION: is the same as RESTRICT.
  • SET DEFAULT: is recognized by the MySQL parser. However, this action is rejected by both InnoDB and NDB tables.

In fact, MySQL fully supports three actions: RESTRICT, CASCADE and SET NULL.

If you don’t specify the ON DELETE and ON UPDATE clause, the default action is RESTRICT.

Let’s create a new database called fkdemo for the demonstration.

CREATE DATABASE fkdemo; USE fkdemo;

Code language: SQL (Structured Query Language) (sql)

RESTRICT & NO ACTION actions

Inside the fkdemo database, create two tables categories and products:

CREATE TABLE categories( categoryId INT AUTO_INCREMENT PRIMARY KEY, categoryName VARCHAR(100) NOT NULL ) ENGINE=INNODB; CREATE TABLE products( productId INT AUTO_INCREMENT PRIMARY KEY, productName varchar(100) not null, categoryId INT, CONSTRAINT fk_category FOREIGN KEY (categoryId) REFERENCES categories(categoryId) ) ENGINE=INNODB;

Code language: SQL (Structured Query Language) (sql)

The categoryId in the products table is the foreign key column that refers to the categoryId column in the  categories table.

Because we don’t specify any ON UPDATE and ON DELETE clauses, the default action is RESTRICT for both update and delete operation.

The following steps illustrate the RESTRICT action.

1) Insert two rows into the categories table:

INSERT INTO categories(categoryName) VALUES ('Smartphone'), ('Smartwatch');

Code language: SQL (Structured Query Language) (sql)

2) Select data from the categories table:

SELECT * FROM categories;

Code language: SQL (Structured Query Language) (sql)

3) Insert a new row into the products table:

INSERT INTO products(productName, categoryId) VALUES('iPhone',1);

Code language: SQL (Structured Query Language) (sql)

It works because the categoryId 1 exists in the categories table.

4) Attempt to insert a new row into the products table with a categoryId  value does not exist in the categories table:

INSERT INTO products(productName, categoryId) VALUES('iPad',3);

Code language: SQL (Structured Query Language) (sql)

MySQL issued the following error:

Error Code: 1452. Cannot add or update a child row: a foreign key constraint fails (`fkdemo`.`products`, CONSTRAINT `fk_category` FOREIGN KEY (`categoryId`) REFERENCES `categories` (`categoryId`) ON DELETE RESTRICT ON UPDATE RESTRICT)

Code language: JavaScript (javascript)

5) Update the value in the categoryId column in the categories table to 100:

UPDATE categories SET categoryId = 100 WHERE categoryId = 1;

Code language: SQL (Structured Query Language) (sql)

MySQL issued this error:

Error Code: 1451. Cannot delete or update a parent row: a foreign key constraint fails (`fkdemo`.`products`, CONSTRAINT `fk_category` FOREIGN KEY (`categoryId`) REFERENCES `categories` (`categoryId`) ON DELETE RESTRICT ON UPDATE RESTRICT)

Code language: JavaScript (javascript)

Because of the RESTRICT option, you cannot delete or update categoryId 1 since it is referenced by the productId 1 in the products table.

CASCADE action

These steps illustrate how ON UPDATE CASCADE and ON DELETE CASCADE actions work.

1) Drop the products table:

DROP TABLE products;

Code language: SQL (Structured Query Language) (sql)

2) Create the products table with the ON UPDATE CASCADE and ON DELETE CASCADE options for the foreign key:

CREATE TABLE products( productId INT AUTO_INCREMENT PRIMARY KEY, productName varchar(100) not null, categoryId INT NOT NULL, CONSTRAINT fk_category FOREIGN KEY (categoryId) REFERENCES categories(categoryId) ON UPDATE CASCADE ON DELETE CASCADE ) ENGINE=INNODB;

Code language: SQL (Structured Query Language) (sql)

3) Insert four rows into the products table:

INSERT INTO products(productName, categoryId) VALUES ('iPhone', 1), ('Galaxy Note',1), ('Apple Watch',2), ('Samsung Galary Watch',2);

Code language: SQL (Structured Query Language) (sql)

4) Select data from the products table:

SELECT * FROM products;

Code language: SQL (Structured Query Language) (sql)

5) Update categoryId 1 to 100 in the categories table:

UPDATE categories SET categoryId = 100 WHERE categoryId = 1;

Code language: SQL (Structured Query Language) (sql)

6) Verify the update:

SELECT * FROM categories;

Code language: SQL (Structured Query Language) (sql)

7) Get data from the products table:

SELECT * FROM products;

Code language: SQL (Structured Query Language) (sql)

As you can see, two rows with value 1 in the categoryId column of the products table were automatically updated to 100 because of the ON UPDATE CASCADE action.

8) Delete categoryId 2 from the categories table:

DELETE FROM categories WHERE categoryId = 2;

Code language: SQL (Structured Query Language) (sql)

9) Verify the deletion:

SELECT * FROM categories;

Code language: SQL (Structured Query Language) (sql)

10) Check the products table:

SELECT * FROM products;

Code language: SQL (Structured Query Language) (sql)

All products with categoryId 2 from the products table were automatically deleted because of the ON DELETE CASCADE action.

SET NULL action

These steps illustrate how the ON UPDATE SET NULL and ON DELETE SET NULL actions work.

1) Drop both categories and products tables:

DROP TABLE IF EXISTS categories; DROP TABLE IF EXISTS products;

Code language: SQL (Structured Query Language) (sql)

2) Create the categories and products tables:

CREATE TABLE categories( categoryId INT AUTO_INCREMENT PRIMARY KEY, categoryName VARCHAR(100) NOT NULL )ENGINE=INNODB; CREATE TABLE products( productId INT AUTO_INCREMENT PRIMARY KEY, productName varchar(100) not null, categoryId INT, CONSTRAINT fk_category FOREIGN KEY (categoryId) REFERENCES categories(categoryId) ON UPDATE SET NULL ON DELETE SET NULL )ENGINE=INNODB;

Code language: SQL (Structured Query Language) (sql)

The foreign key in the products table changed to ON UPDATE SET NULL and ON DELETE SET NULL options.

3) Insert rows into the categories table:

INSERT INTO categories(categoryName) VALUES ('Smartphone'), ('Smartwatch');

Code language: SQL (Structured Query Language) (sql)

4) Insert rows into the products table:

INSERT INTO products(productName, categoryId) VALUES ('iPhone', 1), ('Galaxy Note',1), ('Apple Watch',2), ('Samsung Galary Watch',2);

Code language: SQL (Structured Query Language) (sql)

5) Update categoryId from 1 to 100 in the categories table:

UPDATE categories SET categoryId = 100 WHERE categoryId = 1;

Code language: SQL (Structured Query Language) (sql)

6) Verify the update:

SELECT * FROM categories;

Code language: SQL (Structured Query Language) (sql)

7) Select data from the products table:

The rows with the categoryId 1 in the products table were automatically set to NULL due to the ON UPDATE SET NULL action.

8) Delete the categoryId 2 from the categories table:

DELETE FROM categories WHERE categoryId = 2;

Code language: SQL (Structured Query Language) (sql)

9) Check the products table:

SELECT * FROM products;

Code language: SQL (Structured Query Language) (sql)

The values in the categoryId column of the rows with categoryId 2 in the products table were automatically set to NULL due to the ON DELETE SET NULL action.

Drop MySQL foreign key constraints

To drop a foreign key constraint, you use the ALTER TABLE statement:

ALTER TABLE table_name DROP FOREIGN KEY constraint_name;

Code language: SQL (Structured Query Language) (sql)

In this syntax:

  • First, specify the name of the table from which you want to drop the foreign key after the ALTER TABLE keywords.
  • Second, specify  the constraint name after the DROP FOREIGN KEY keywords.

Notice that constraint_name is the name of the foreign key constraint specified when you created or added the foreign key constraint to the table.

To obtain the generated constraint name of a table, you use the SHOW CREATE TABLE statement:

SHOW CREATE TABLE table_name;

Code language: SQL (Structured Query Language) (sql)

For example, to see the foreign keys of the products table, you use the following statement:

SHOW CREATE TABLE products;

Code language: SQL (Structured Query Language) (sql)

The following is the output of the statement:

As you can see clearly from the output, the table products table has one foreign key constraint: fk_category

And this statement drops the foreign key constraint of the products table:

ALTER TABLE products DROP FOREIGN KEY fk_category;

Code language: SQL (Structured Query Language) (sql)

To ensure that the foreign key constraint has been dropped, you can view the structure of the products table:

SHOW CREATE TABLE products;

Code language: SQL (Structured Query Language) (sql)

MySQL Foreign Key - after drop foreign key constraint

Disabling foreign key checks

Sometimes, it is very useful to disable foreign key checks e.g., when you import data from a CSV file into a table. If you don’t disable foreign key checks, you have to load data into a proper order i.e., you have to load data into parent tables first and then child tables, which can be tedious. However, if you disable the foreign key checks, you can load data into tables in any order.

To disable foreign key checks, you use the following statement:

SET foreign_key_checks = 0;

Code language: SQL (Structured Query Language) (sql)

And you can enable it by using the following statement:

SET foreign_key_checks = 1;

Code language: SQL (Structured Query Language) (sql)

In this tutorial, you have learned about the MySQL foreign key and how to create a foreign key constraint with various reference options.

Was this tutorial helpful?

Понравилась статья? Поделить с друзьями:
  • Как изменить dns на роутере xiaomi
  • Как изменить footer section
  • Как изменить dns на ноутбуке
  • Как изменить fn клавиши на ноутбуке настройки
  • Как изменить dns на виндовс 10