Search code examples
mysqlrandomgeneric-foreign-key

How to generate foreign key names random which are not exist in database?


Suppose I am writing query like this.

SET foreign_key_checks = 0;

ALTER TABLE `StudentSubjectMarkMap` 
  ADD CONSTRAINT `here_I_want_some_random_name`
  FOREIGN KEY (`id` )
  REFERENCES `Subject` (`subjectId` )
  ON DELETE NO ACTION
  ON UPDATE NO ACTION
, ADD INDEX `here_I_want_some_random_name` (`id` ASC);

SET foreign_key_checks = 1;

My Question is "is it possible to generate some random String name as foreign key name?" I want such thing because this query is giving me duplicate key name error even after I dropped that key name.


Solution

  • Index name is optional, so you don't need to specify it. In that case MySQL will assign a name for the index and it doesn't fail. See ALTER TABLE syntax for more details:

    ALTER [ONLINE | OFFLINE] [IGNORE] TABLE tbl_name
        [alter_specification [, alter_specification] ...]
        [partition_options]
      ADD {INDEX|KEY} [index_name]
            [index_type] (index_col_name,...) [index_option] ...
      ADD [CONSTRAINT [symbol]]
        FOREIGN KEY [index_name] (index_col_name,...)
        reference_definition