Combine Columns Before Matching with LIKE in a Single Query in MySQL



You can use CONCAT() function for this. Let us first create a table −

mysql> create table DemoTable
   (
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   Value1 varchar(10),
   Value2 varchar(10)
   );
Query OK, 0 rows affected (0.21 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable(Value1,Value2) values('10','345');
Query OK, 1 row affected (0.07 sec)

mysql> insert into DemoTable(Value1,Value2) values('14','789');
Query OK, 1 row affected (0.06 sec)

mysql> insert into DemoTable(Value1,Value2) values('18','234');
Query OK, 1 row affected (0.13 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+----+--------+--------+
| Id | Value1 | Value2 |
+----+--------+--------+
| 1  | 10     | 345    |
| 2  | 14     | 789    |
| 3  | 18     | 234    |
+----+--------+--------+
3 rows in set (0.00 sec)

Following is the query to combine columns before matching it with LIKE in a single query −

mysql> SELECT * FROM DemoTable WHERE CONCAT(Value1, Value2) LIKE '%147%';

This will produce the following output −

+----+--------+--------+
| Id | Value1 | Value2 |
+----+--------+--------+
| 2  | 14     | 789    |
+----+--------+--------+
1 row in set (0.00 sec)
Updated on: 2019-07-30T22:30:26+05:30

135 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements