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 open–source 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.