Tirath
Tirath

Reputation: 2404

Difference between add constraint syntax in MySQL?

So, I am applying foreign key constraint on a column in MySQL table.

What I noticed is that I am able to do that in two ways -

ALTER TABLE book ADD CONSTRAINT fk_code_id FOREIGN KEY(book_type) REFERENCES code(id);

and

ALTER TABLE book ADD FOREIGN KEY(book_type) REFERENCES code(id);

Why do we have two ways in place to achieve same thing?

Upvotes: 1

Views: 549

Answers (2)

ramprasath .n
ramprasath .n

Reputation: 100

create a FOREIGN KEY constraint on the "PersonID" column when the "Orders" table is already created, use the following SQL:

MySQL / SQL Server / Oracle / MS Access:

ALTER TABLE Orders
ADD FOREIGN KEY (PersonID) REFERENCES Persons(PersonID);

To allow naming of a FOREIGN KEY constraint, and for defining a FOREIGN KEY constraint on multiple columns, use the following SQL syntax:

MySQL / SQL Server / Oracle / MS Access:

ALTER TABLE Orders
ADD CONSTRAINT FK_PersonOrder
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID);

Upvotes: 1

Sachin Shah
Sachin Shah

Reputation: 4533

Alter table with Constraint option for adding check constraints to MySQL database tables. The add constraint function allows the user to add a constraint name and a constraint condition.

https://razorsql.com/features/mysql_add_constraint.html

And by this ALTER TABLE book ADD FOREIGN KEY(book_type) REFERENCES code(id) you just make fk between two tables.

Upvotes: 2

Related Questions