3

I can't seem to find an answer to this one:

Say I have a table like so:

ID   Name
------------------------
1    AAAAAAAAA
2    ABAAAAAAA
3    BBAAAAAAA
4    CDAAAAAAA
5    BBAAAAAAA

Is there a way I can order by name - but - start that order from say BB and let it loop back round (instead of from A-Z, go from BB to BA)

The final result would then be:

3    BBAAAAAAA
5    BBAAAAAAA
4    CDAAAAAAA
1    AAAAAAAAA
2    ABAAAAAAA

Does that make sense?

2 Answers 2

3

If you want the BB to appear at the beginning you can use:

select *
from yourtable
order by case when substring(name, 1, 2) = 'BB' then 0 else 1 end

See SQL Fiddle with Demo

If you want CD to appear second, then use:

select *
from yourtable
order by 
  case 
    when substring(name, 1, 2) = 'BB' then 0 
    when substring(name, 1, 2) = 'CD' then 1 
    else 2 end, name

See SQL Fiddle with Demo

Result for second query:

| ID |      NAME |
------------------
|  3 | BBAAAAAAA |
|  5 | BBAAAAAAA |
|  4 | CDAAAAAAA |
|  1 | AAAAAAAAA |
|  2 | ABAAAAAAA |
Sign up to request clarification or add additional context in comments.

7 Comments

order by substring(name, 1, 2) = 'BB' DESC should also work - is there any bad practice about this, and is case when preferred? Update: With your update it makes a lot more sense to use case. Nevermind. :-)
@h2ooooooo if they only have one to order by then you can order by desc but if you have a several specific orders then you can use case
This is actually perfect for what I need - thanks! Will accept as soon as I can.
this will put BB and CD strings at the top, unordered, and every other row unordered ad the bottom.. i am not sure this is what the OP wants
It's not what the question was exactly - however it does solve my actual problem perfectly, so I'm accepting it on the basis that @bluefeet is psychic.
|
1

This will order all rows by name. It will first put rows >= 'BB' ordered by name, and then rows < 'BB' also ordered by name, making it loop the way you want:

select *
from your_table
order by name<'BB', name

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.