Is it required to specify a Constraint Name when adding a Foreign Key in MySQL?

Viewed 35

So far I've created the tables manually like this and I didn't have any issues.

  CREATE TABLE users (
    id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
    email VARCHAR(100) NOT NULL,
    cityId BIGINT(20) UNSIGNED NULL DEFAULT NULL,
  PRIMARY KEY (id),
    FOREIGN KEY (cityId)
    REFERENCES cities (id));

Now, I'm using MySQL Workbench that generates the SQL Script for me, and the SQL script looks a bit different.

  CREATE TABLE users (
    id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
    email VARCHAR(100) NOT NULL,
    cityId BIGINT(20) UNSIGNED NULL DEFAULT NULL,
  PRIMARY KEY (id),
  CONSTRAINT cityId
     FOREIGN KEY (cityId)
     REFERENCES locations (id)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION);

I'm wondering if there is any difference between these two queries.

1 Answers

You are not required to provide a name for a foreign key, and if you don't, an autogenerated name will be assigned to it. Having said that, it's a good practice and will make your maintenance work easier.

Related