Home >Database >Mysql Tutorial >How do I add a string to the beginning of values in a MySQL column?

How do I add a string to the beginning of values in a MySQL column?

Susan Sarandon
Susan SarandonOriginal
2024-11-17 15:50:02922browse

How do I add a string to the beginning of values in a MySQL column?

Prepending a String to Column Values in MySQL

Updating a column's value to include a prepended string in MySQL requires a tailored SQL update statement. Suppose you need to add "test" to the beginning of an existing value in a specific field across multiple rows.

To achieve this, the CONCAT function comes to your aid. It allows you to concatenate multiple strings together.

UPDATE tbl SET col=CONCAT('test',col);

This query updates the "col" field in the "tbl" table by prefixing the existing value with "test." For instance, if the current value of "col" is "try," it will become "testtry."

However, if you want to ensure that "test" is not prepended to values that already contain it, you can utilize a more refined approach:

UPDATE tbl SET col=CONCAT('test',col)
WHERE col NOT LIKE 'test%';

This enhanced query employs the LIKE operator to check if the existing value does not start with "test." This allows for selective updates, maintaining the integrity of existing values that already meet the desired criteria.

The above is the detailed content of How do I add a string to the beginning of values in a MySQL column?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn