Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ordering sql query by first letter

I am trying to order my mysql queries based on the first letter but every method I have used is restricting my search.

Example MySQL table Value computer services abc computer services dynamic computer services

If I search for computer services I want the results to returned as:

**Name**
computer services
abc computer services
dynamic computer services

I am using mysql fullsearch text but if i use name LIKE 'c%' I don't the other two results e.g.

SELECT name FROM table WHERE match('name') against('computer services*' IN BOOLEAN MODE) AND name LIKE 'c%';

This would only return

  • computer services

But I want it to return:

  • computer services
  • abc computer services
  • dynamic computer services

I am new to mysql full search text.

like image 347
James Bell Avatar asked Feb 08 '11 16:02

James Bell


People also ask

How do I sort the first letter in SQL?

The SUBSTR function can return the first character of a string. SUBSTR takes three parameters, the field to sort, the 1-based start position, and the number of characters to return.

How do I order a to z in SQL?

By default, ORDER BY without any additional specifier sorts in ascending order (equivalent to using the ASC keyword explicitly). As you can probably guess, ASC stands for “ascending.” If you'd like to sort in descending order, simplify specify the DESC keyword after the column name.

How do I order queries in SQL?

The ORDER BY statement in SQL is used to sort the fetched data in either ascending or descending according to one or more columns. By default ORDER BY sorts the data in ascending order. We can use the keyword DESC to sort the data in descending order and the keyword ASC to sort in ascending order.


1 Answers

Use an order by clause that matches the 'starts with' case first. I'm using not like here because the boolean returns 0 or 1 and we want to reverse that to match the starts with case first.

SELECT name 
FROM table 
WHERE match('name') against('computer services*' IN BOOLEAN MODE)
ORDER BY name NOT LIKE 'computer services%', name;
like image 200
a'r Avatar answered Oct 07 '22 09:10

a'r