Is it possible to delete everything after a 'space' in a MySQL field?

MySQLMySQLi Database

In order to delete everything after a space, you need to use SUBSTRING_INDEX().

The syntax is as follows

select substring_index(yourColumnName,' ',1) as anyAliasName from yourTableName;

To understand the above syntax, let us create a table. The query to create a table is as follows

mysql> create table deleteAfterSpaceDemo
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> StudentName varchar(100)
   -> );
Query OK, 0 rows affected (0.55 sec)

Insert some records in the table using insert command.

The query is as follows

mysql> insert into deleteAfterSpaceDemo(StudentName) values('John Smith');
Query OK, 1 row affected (0.15 sec)
mysql> insert into deleteAfterSpaceDemo(StudentName) values('Adam Smith');
Query OK, 1 row affected (0.14 sec)
mysql> insert into deleteAfterSpaceDemo(StudentName) values('Carol Taylor');
Query OK, 1 row affected (0.18 sec)
mysql> insert into deleteAfterSpaceDemo(StudentName) values('Chris Brown');
Query OK, 1 row affected (0.14 sec)
mysql> insert into deleteAfterSpaceDemo(StudentName) values('David Miller');
Query OK, 1 row affected (0.15 sec)

Display all records from the table using select statement.

The query is as follows

mysql> select *from deleteAfterSpaceDemo;

The following is the output

+----+--------------+
| Id | StudentName  |
+----+--------------+
| 1  | John Smith   |
| 2  | Adam Smith   |
| 3  | Carol Taylor |
| 4  | Chris Brown  |
| 5  | David Miller |
+----+--------------+
5 rows in set (0.00 sec)

Here is the query to delete everything after a space

mysql> select substring_index(StudentName,' ',1) as deleteAllAfterSpace from deleteAfterSpaceDemo;

The following is the output

+---------------------+
| deleteAllAfterSpace |
+---------------------+
| John                |
| Adam                |
| Carol               |
| Chris               |
| David               |
+---------------------+
5 rows in set (0.04 sec)
raja
Published on 29-Mar-2019 09:53:29
Advertisements