Use the LOCATE() and SUBSTRING() method for this in MySQL. Let us first create a table −
mysql> create table DemoTable -> ( -> Title text -> ); Query OK, 0 rows affected (0.54 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('Introduction To Java'); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable values('Introduction - To MySQL'); Query OK, 1 row affected (0.16 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
Output
This will produce the following output −
+-------------------------+ | Title | +-------------------------+ | Introduction To Java | | Introduction - To MySQL | +-------------------------+ 2 rows in set (0.00 sec)
Following is the query to display a substring before a special character in a substring −
mysql> select distinct -> if(LOCATE(' - ',Title)>0, SUBSTRING(Title, 1, LOCATE(' - ', Title)), Title) from DemoTable;
Output
This will produce the following output −
+-----------------------------------------------------------------------------+ | if(LOCATE(' - ',Title)>0, SUBSTRING(Title, 1, LOCATE(' - ', Title)), Title) | +-----------------------------------------------------------------------------+ | Introduction To Java | | Introduction | +-----------------------------------------------------------------------------+ 2 rows in set (0.00 sec)