Search code examples
mysqldatabaseprimary-keyunique-constraintalter

ALTER Query Not Working


I have two tables: cleanup and uniqueEntries. They both have an auto-increment id as primary key. The table structure of uniqueEntries comes from cleanup as such:

$sql = "CREATE TABLE uniqueEntries LIKE cleanup"; //create table to store all unique entries
doQuery($sql, "success creating uniqueEntries", "failed creating uniqueEntries"); //perform query

Table cleanup contains duplicate usernames. As I am moving data into uniqueEntries, I want to make sure I am not inserting any duplicates. So I need to implement an ALTER statement on User_ID. I did that as such:

$sql = "ALTER IGNORE TABLE uniqueEntries ADD UNIQUE (User_ID)"; //make User_ID unique
doQuery($sql, "success adding constraint to uniqueEntries", "failed adding constraint to uniqueEntries"); //perform query

However, unlike all of my other queries the ALTER query does not get processed. I get failed adding constraint to uniqueEntries. What am I doing wrong?

Below is my doQuery function:

function doQuery($sql, $success, $fail){
    global $conn;
        if ($conn->query($sql) === TRUE) {
        eLog( $success ); //log outcome
    } else {
        eLog( $fail ); //log outcome
    } 
}

Solution

  • I followed @Marc B's advice to output the message from $conn()->error and learned that TEXT column type does not allow ALTER operations.

    BLOB/TEXT column 'User_ID' used in key specification without a key length
    

    So, I went back to my table query and switched the User_ID column from TEXT to VARCHAR(15) and I was able to run the ALTER query without problems.