Question: I had previously written my `create` queries as follows, where the foreign keys were unnamed. 

```
CREATE TABLE My_Table_Name (
    USER_ID VARCHAR(255) NOT NULL,
    CONSENT_ID VARCHAR(255)  NOT NULL,
    PRIMARY KEY (USER_ID, CONSENT_ID),
    FOREIGN KEY (CONSENT_ID) REFERENCES ANOTHER_TABLE_NAME (CONSENT_ID) ON DELETE CASCADE
);

```

Now the table has data in it and I want to add the constraint name to the existing foreign keys. How can I do that? 

**PS: What I need is an `ALTER` query**

Also, if the database were SQL Server instead of MySQL, would the query be different?

Answer: 
Foreign key constraints in MySQL cannot be renamed once created. You will have to drop the constraint, then recreate it with the name you want.

First you are going to have to go digging for the foreign key constraint name (there is one, you just don't know what it is):

```
SELECT constraint_name
FROM information_schema.REFERENTIAL_CONSTRAINTS
WHERE constraint_schema = 'your_db_name' AND table_name = 'My_Table_Name';

```

Now rename the constraint:

```
ALTER TABLE My_Table_Name
DROP FOREIGN KEY some_foreign_key    -- from above query
ADD CONSTRAINT fk_my_constraint FOREIGN KEY (CONSENT_ID)
    REFERENCES ANOTHER_TABLE_NAME (CONSENT_ID) ON DELETE CASCADE;

```
In MS SQL, anonymous constraints will get a system generated name.

You could use the following query to fetch the generated constraint name:

```
SELECT
    FK.CONSTRAINT_NAME
FROM
    INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS RC
    INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK ON
        PK.CONSTRAINT_CATALOG = RC.UNIQUE_CONSTRAINT_CATALOG AND
        PK.CONSTRAINT_SCHEMA = RC.UNIQUE_CONSTRAINT_SCHEMA AND
        PK.CONSTRAINT_NAME = RC.UNIQUE_CONSTRAINT_NAME
    INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS FK ON
        FK.CONSTRAINT_CATALOG = RC.CONSTRAINT_CATALOG AND
        FK.CONSTRAINT_SCHEMA = RC.CONSTRAINT_SCHEMA AND
        FK.CONSTRAINT_NAME = RC.CONSTRAINT_NAME
WHERE
    FK.TABLE_NAME = N'My_Table_Name' AND
    PK.TABLE_NAME = N'ANOTHER_TABLE_NAME'

```

This gives a result like 'FK\_\_My\_Table\_\_\_CONSE\_\_5535A963'.

Next, you might use the `sp_rename` stored procedure, like this:

```
EXECUTE sp_rename N'FK__My_Table___CONSE__5535A963', N'FK_MyRenamedConstraint';

```

Of course, you need to use the correct constraint names in your query.

(You may ignore the default warning from SQL Server about the fact that renaming might break existing scripts and stored procedures.)

When the first query is executed again, it will show you the new name.

I do not know how all this should be done in MySQL... Sorry about that...