Add Foreign Key to a Table

To add a foreign key to a table in MariaDB we need to ensure that the referenced columns in the related table have a primary key or a unique key constraint.

Syntax:

CREATE TABLE table_name(columns_list,
.....
FOREIGN KEY (column_name) REFERENCES parent_table_name(column_name)

Explanation:

  • CREATE TABLE table_name: This part create a new table and give the name of the table.
  • columns_list: There will be the list of columns and their data types that you want to include in the table.
  • CONSTRAINT [constraint_name]: Specify the name of the foreign key constraint after the constraint keyword.
  • FOREIGN KEY [fk_name] (col_name): Specify the name of the foreign key followed by a list of comma-separated column names placed within parentheses. The foreign key name is optional.
  • REFRENCES parent_table_name (col_name): Specifies the referenced table and column that the foreign key in the current table refers to.

Foreign Key in MariaDB

MariaDB is an opensource database system which is similar to MySQL. It provide various features such as high availability and vertical scalability to allow database to scale up over various nodes or single node as features like Galera Cluster in MariaDB. The Foreign keys are the most important features that help define and establish relationships between tables. In this article, we will what is Foreign Key, its syntax various methods to define a Foreign Key, and examples.

Similar Reads

Introduction to FOREIGN KEY in MariaDB

FOREIGN KEY stands for a column or the set of columns table that creates a foreign key connection to the primary key or unique index in another table. It is important for the basis of referential integrity which ensures data relationships remain consistent across tables....

Add Foreign Key to a Table

To add a foreign key to a table in MariaDB we need to ensure that the referenced columns in the related table have a primary key or a unique key constraint....

Setting Up Environment

Let’s create tables and add foreign key to them:...

MariaDB Foreign Key Constraint Examples

Let’s understand through some examples of using a foreign key constraint with various reference options....

Conclusion

In MariaDB, foreign keys is important constrainnts for ensuring data consistency and table relations. Foreign keys also help in implementing referential integrity which ensures that the database is consistent and reliable. In this article we have seen how to define, insert and delete foreign keys enables database administrators in designing as well as managing databases schemas....

Contact Us