To remove the first two characters of all fields, you need to use SUBSTRING() function from MySQL. The syntax is as follows −
UPDATE yourTableName SET yourColumnName=SUBSTRING(yourColumnName,3) WHERE yourCondition;
To understand the above syntax, let us create a table. The query to create a table is as follows −
mysql> create table RemoveFirstTwoCharacterDemo -> ( -> Id int NOT NULL AUTO_INCREMENT, -> StringValue varchar(30), -> PRIMARY KEY(Id) -> ); Query OK, 0 rows affected (1.04 sec)
Insert some records in the table using insert command. The query is as follows −
mysql> insert into RemoveFirstTwoCharacterDemo(StringValue) values('U:100'); Query OK, 1 row affected (0.13 sec) mysql> insert into RemoveFirstTwoCharacterDemo(StringValue) values('S:20'); Query OK, 1 row affected (0.21 sec) mysql> insert into RemoveFirstTwoCharacterDemo(StringValue) values('N/A'); Query OK, 1 row affected (0.12 sec) mysql> insert into RemoveFirstTwoCharacterDemo(StringValue) values('T:8'); Query OK, 1 row affected (0.16 sec) mysql> insert into RemoveFirstTwoCharacterDemo(StringValue) values('N/A'); Query OK, 1 row affected (0.12 sec) mysql> insert into RemoveFirstTwoCharacterDemo(StringValue) values('W:99'); Query OK, 1 row affected (0.19 sec)
Display all records from the table using a select statement. The query is as follows −
mysql> select *from RemoveFirstTwoCharacterDemo;
The following is the output −
+----+-------------+ | Id | StringValue | +----+-------------+ | 1 | U:100 | | 2 | S:20 | | 3 | N/A | | 4 | T:8 | | 5 | N/A | | 6 | W:99 | +----+-------------+ 6 rows in set (0.00 sec)
The following is the query to remove the first two characters −
mysql> update RemoveFirstTwoCharacterDemo set StringValue=SUBSTRING(StringValue,3) -> where StringValue <> 'N/A'; Query OK, 4 rows affected (0.27 sec) Rows matched: 4 Changed: 4 Warnings: 0
Check the table records once again using a select statement. The query is as follows −
mysql> select *from RemoveFirstTwoCharacterDemo;
The following is the output −
+----+-------------+ | Id | StringValue | +----+-------------+ | 1 | 100 | | 2 | 20 | | 3 | N/A | | 4 | 8 | | 5 | N/A | | 6 | 99 | +----+-------------+ 6 rows in set (0.00 sec)