Home > Blockchain >  SQL - How to order by how close a character is to the beginning of the word
SQL - How to order by how close a character is to the beginning of the word

Time:03-11

I am a beginner to web development and I would like to know if there is a way to order my query by how close a character is to the beginning of the word.

By this I mean:

Let's say that I have a query with all the entries sharing an 'a' I want to order the entries by how close the 'a' is at the beginning of the word.

So if this was my query:

´walk´
´Andrew´
´leaf´
´umbrella´
´michael´

It would be ordered like this:

´Andrew´
´walk´
´leaf´
´michael´
´umbrella´

Can anyone help me?

CodePudding user response:

You could do it this way by first finding the position of the substring (a) and then ordering by that position (updated to exclude words with no a):

select word, position('a' in word) as position
from words
having position > 0
order by position asc

http://sqlfiddle.com/#!9/15350a/2

CodePudding user response:

select   word
from     words
order by ifnull(nullif(position('a' in word),0),999999999999)
word
Andrew
walk
leaf
michael
umbrella
bcdefg

Fiddle

  • Related