Showing posts with label sql foreign key. Show all posts
Showing posts with label sql foreign key. Show all posts

Wednesday, 31 May 2023

MySQL foreign key example

MySQL does support foreign keys, but only on the InnoDB storage engine. The MyISAM storage engine does not support foreign keys.

Foreign keys are a way to enforce referential integrity in a database. They allow you to specify that a value in one table must be the same as a value in another table. This helps to prevent errors and inconsistencies in your data.

To create a foreign key in MySQL, you use the FOREIGN KEY constraint in the CREATE TABLE statement. For example:


CREATE TABLE customers (

  customer_id INT NOT NULL AUTO_INCREMENT,

  customer_name VARCHAR(255) NOT NULL,

  PRIMARY KEY (customer_id)

);


CREATE TABLE orders (

  order_id INT NOT NULL AUTO_INCREMENT,

  customer_id INT NOT NULL,

  order_date DATETIME NOT NULL,

  PRIMARY KEY (order_id),

  FOREIGN KEY (customer_id) REFERENCES customers (customer_id)

);


In this example, the customer_id column in the orders table is a foreign key that references the customer_id column in the customers table. This means that a value in the customer_id column in the orders table must also exist in the customer_id column in the customers table.

If you try to insert a value in the customer_id column in the orders table that does not exist in the customer_id column in the customers table, MySQL will reject the insert operation.

Foreign keys are an important part of database design. They help to ensure the integrity of your data and prevent errors. If you are using MySQL, I recommend using the InnoDB storage engine and creating foreign keys in your tables.