Skip to content

Coder Tutorial

Menu
  • Home
  • HTML
  • CSS
  • PHP
  • SQL
  • MySQL
  • JS
  • PL/SQL
  • Python
  • Java
  • Oracle
Home
MySQL
MySQL Add constraint foreign key

MySQL Add constraint foreign key

MySQL Add constraint foreign key

Add foreign key to MySQL table using alter table syntax and add constraint keyword.

MySQL Add constraint foreign key syntax

ALTER TABLE table_nameB ADD CONSTRAINT constraint_name FOREIGN KEY (column_name) REFERENCES table_nameA (column_name);

Add constraint foreign key example

ALTER TABLE `books` 
ADD CONSTRAINT fk_product_id 
FOREIGN KEY (product_id) 
REFERENCES `products` (id);

Output

table `books` altered.

Tutorials

  • MySQL Tutorial
  • Database
  • Data Types
  • Insert
  • Update
  • Delete
  • Select
  • Clauses
  • Where
  • AND
  • OR
  • IN
  • Between
  • Order By
  • Limit
  • Flow Control Statements
  • CASE
  • IF
  • Iterate
  • Leave
  • Loop
  • Repeat
  • Return
  • While
  • Functions and Operators
  • Table
  • View
  • Temporary Table
  • Triggers
  • Procedure
  • Function
  • Indexes
  • Transactions
  • Create trigger
  • Create table
  • Drop table
  • Add column
  • Drop column
  • Rename column
  • Add primary key
  • Add constraint foreign key
  • Drop foreign key
  • Add index
  • Drop index

Recent Posts

  • Java Polymorphism
  • Java Encapsulation
  • Java Abstraction
  • PostgreSQL ERROR: cannot begin/end transactions in PL/pgSQL
  • PostgreSQL Column must appear in the GROUP BY clause
  • PostgreSQL Column specified more than once
  • PostgreSQL Create database, Alter database examples
  • PostgreSQL Create schema syntax, Alter schema
  • PostgreSQL Create database user, alter and drop username
  • PostgreSQL Alter table name. Modify column name
Coder Tutorial Copyright © 2025. | Privacy Policy
Back to Top ↑