Search results
The FOREIGN KEY constraint is used to prevent actions that would destroy links between tables. A FOREIGN KEY is a field (or collection of fields) in one table, that refers to the PRIMARY KEY in another table.
To add a foreign key (grade_id) to an existing table (users), follow the following steps: ALTER TABLE users ADD grade_id SMALLINT UNSIGNED NOT NULL DEFAULT 0; ALTER TABLE users ADD CONSTRAINT fk_grade_id FOREIGN KEY (grade_id) REFERENCES grades(id);
A foreign key is a column (or set of columns) that establishes a relationship between data in two tables. The primary key column (or columns) of the first table is referenced by the column (or columns) of the second table in a foreign key reference.
This tutorial introduces you to MySQL foreign key constraints and shows you how to manage foreign keys effectively.
You can add a foreign key constraint to an existing table using the following ALTER TABLE syntax: ALTER TABLE tbl_name ADD [CONSTRAINT [symbol]] FOREIGN KEY [index_name] (col_name, ...) REFERENCES tbl_name (col_name,...) [ON DELETE reference_option] [ON UPDATE reference_option]
8 kwi 2021 · 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);
Learn how to use the FOREIGN KEY constraint to link two tables together in SQL. See examples of creating, naming, and dropping FOREIGN KEY constraints in MySQL and other databases.