Search code examples
mysqlspecial-characterscase-sensitive

Replace space with underscore in table


How can I write a SQL query to replace all occurrences of space in a table with underscore and set all characters to lowercase?


Solution

  • To update a single column in a single table, you can use a combination of LOWER() and REPLACE():

    UPDATE table_name SET column_name=LOWER(REPLACE(column_name, ' ', '_'))
    

    To "duplicate" the existing column, and perform the updates on the duplicate (per your question in a comment), you can use MySQL's ALTER command before the UPDATE query:

    ALTER TABLE table_name ADD duplicate_column_name VARCHAR(255) AFTER column_name;
    UPDATE table_name SET duplicate_column_name = LOWER(REPLACE(column_name, ' ', '_'));
    

    Just be sure to update the data-type in the ALTER command to reflect your actual data-type.