Display substrings of different length with a single MySQL query and combine the result

MySQLMySQLi Database

Let us first create a table −

mysql> create table DemoTable856(Title text);
Query OK, 0 rows affected (0.89 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable856 values('Introduction to MySQL');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable856 values('Java in depth');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable856 values('C++ with Data Structure');
Query OK, 1 row affected (0.17 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable856;

This will produce the following output −

+-------------------------+
| Title                   |
+-------------------------+
| Introduction to MySQL   |
| Java in depth           |
| C++ with Data Structure |
+-------------------------+
3 rows in set (0.00 sec)

Following is the query to display the substrings of different length and combine the result using UNION ALL −

mysql> select substr(Title,1,12) from DemoTable856
   UNION ALL
   select substr(Title,1,4) from DemoTable856;

This will produce the following output −

+--------------------+
| substr(Title,1,12) |
+--------------------+
| Introduction       |
| Java in dept       |
| C++ with Dat       |
| Intr               |
| Java               |
| C++                |
+--------------------+
6 rows in set (0.03 sec)
raja
Published on 03-Sep-2019 12:26:31
Advertisements