Multiple LIKE Operators with ORDER BY in MySQL?


Following is the syntax implementing multiple LIKE operators with ORDER BY −

select *from yourTableName
order by
(
   yourColumnName like '%yourValue1%'
)
+
(
   yourColumnName like '%yourValue2%'
)
+
.
.
N
desc;

Let us create a table −

mysql> create table demo2
−> (
−> id int not null auto_increment,
−> name varchar(100),
−> primary key(id)
−> );
Query OK, 0 rows affected (1.53 sec)

Insert some records into the table with the help of insert command −

mysql> insert into demo2(name) values('John');
Query OK, 1 row affected (0.18 sec)

mysql> insert into demo2(name) values('David');
Query OK, 1 row affected (0.09 sec)

mysql> insert into demo2(name) values('John Smith');
Query OK, 1 row affected (0.10 sec)

mysql> insert into demo2(name) values('John Doe');
Query OK, 1 row affected (0.11 sec)

mysql> insert into demo2(name) values('David Miller');
Query OK, 1 row affected (0.13 sec)

mysql> insert into demo2(name) values('Chris');
Query OK, 1 row affected (0.09 sec)

mysql> insert into demo2(name) values('Bob Doe');
Query OK, 1 row affected (0.09 sec)

Display records from the table using select statement −

mysql> select *from demo2;

This will produce the following output −

+----+--------------+
| id | name         |
+----+--------------+
|  1 | John         |
|  2 | David        |
|  3 | John Smith   |
|  4 | John Doe     |
|  5 | David Miller |
|  6 | Chris        |
|  7 | Bob Doe      |
+----+--------------+
7 rows in set (0.00 sec)

Following is the query for multiple LIKE operators −

mysql> select *from demo2
−> order by
−> (
−> name like '%Doe%'
−> )
−> +
−> (
−> name like '%David%'
−> ) desc;

This will produce the following output −

+----+--------------+
| id | name         |
+----+--------------+
|  2 | David        |
|  4 | John Doe     |
|  5 | David Miller |
|  7 | Bob Doe      |
|  1 | John         |
|  3 | John Smith   |
|  6 | Chris        |
+----+--------------+
7 rows in set (0.00 sec)

Updated on: 19-Nov-2020

133 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements