go-gorm/gorm · error

failed to create index with name %s

Error message

failed to create index with name %s

What it means

Error "failed to create index with name %s" thrown in go-gorm/gorm.

Source

Thrown at migrator/migrator.go:865

			}
			createIndexSQL += "INDEX ? ON ??"

			if idx.Type != "" {
				createIndexSQL += " USING " + idx.Type
			}

			if idx.Comment != "" {
				createIndexSQL += fmt.Sprintf(" COMMENT '%s'", idx.Comment)
			}

			if idx.Option != "" {
				createIndexSQL += " " + idx.Option
			}

			return m.DB.Exec(createIndexSQL, values...).Error
		}

		return fmt.Errorf("failed to create index with name %s", name)
	})
}

// DropIndex drop index `name`
func (m Migrator) DropIndex(value interface{}, name string) error {
	return m.RunWithValue(value, func(stmt *gorm.Statement) error {
		if stmt.Schema != nil {
			if idx := stmt.Schema.LookIndex(name); idx != nil {
				name = idx.Name
			}
		}

		return m.DB.Exec("DROP INDEX ? ON ?", clause.Column{Name: name}, m.CurrentTable(stmt)).Error
	})
}

// HasIndex check has index `name` or not
func (m Migrator) HasIndex(value interface{}, name string) bool {

View on GitHub (pinned to 1d6ce99528)

Solutions

  1. Check the index name is valid for the database (length and character limits).
  2. Drop the conflicting existing index with that name before creating it.
  3. Ensure the columns referenced by the index exist on the table.

Example fix

Check the index name is unique and valid before CreateIndex: if !db.Migrator().HasIndex(&m, name) { db.Migrator().CreateIndex(&m, name) }

When it happens

Trigger: Thrown at migrator/migrator.go:865 when the library encounters an invalid state.

Common situations: See trigger scenarios.


AI-assisted analysis of go-gorm/gorm@1d6ce99528 (2026-08-15). Data as JSON: /api/errors/fea80b654e90f13b. Report an issue: GitHub.