0

I have a table and I’m trying to filter values with “apple m” on name

select * from table where name like '%apple%m%'
+-------+-------------------------------+------------------------+
|  id   |             name              |          cat           |
+-------+-------------------------------+------------------------+
|  2757 | Apple MacBook                 | Laptops & Accessories  |
|  2777 | Apple Bottom Tops             | Western Wear           |
|  2752 | Apple Monitors                | Desktop Components     |
|  2756 | Apple Desktop & Monitors      | Desktops & Accessories |
|  2778 | Apple Bottom Tunics           | Tops                   |
|  2776 | Apple Selector & Smart Box    | Video & TV Accessories |
|  2787 | Apple Pie Pyjamas             | Girl Clothes           |
|  2773 | Apple Selector & Smart Box    | TV & Video Accessories |
|  2780 | Apple Fun Card Games          | Toys                   |
| 38304 | Snapple Mixer juicer grinders | Kitchen Appliances     |
+-------+-------------------------------+------------------------+

I want to sort display values which start with “apple” and “m” like below:

+------+--------------------------+------------------------+
|  id  |           name           |          cat           |
+------+--------------------------+------------------------+
| 2757 | Apple MacBook            | Laptops & Accessories  |
| 2752 | Apple Monitors           | Desktop Components     |
| 2756 | Apple Desktop & Monitors | Desktops & Accessories |
|      | ---Rest all after this-- |                        |
+------+--------------------------+------------------------+
Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
Manoj
  • 5
  • 4

2 Answers2

1

Use:

ORDER BY name LIKE 'Apple%m%' DESC, name ASC

name LIKE 'Apple%m%' is 1 when name matches the pattern, 0 when it doesn't, so this will order the matching names first. Then it will order by the name within each of those groups.

Barmar
  • 741,623
  • 53
  • 500
  • 612
0

I think you can use something simple like the following:

SELECT * FROM your_table WHERE name LIKE 'apple% m%' ORDER BY name;

The above query first will get rows with name starting by 'apple ' and then will order the results.

If you need case sensitivity then you can use:

SELECT * FROM your_table WHERE name LIKE 'Apple% m%' COLLATE utf8_bin ORDER BY name;

Case sensitivity in like

Community
  • 1
  • 1
Kostas Mitsarakis
  • 4,772
  • 3
  • 23
  • 37