Question

I need to implement custom ordering for my table. For example I have a table called "TestTest" with values: a, d01, d04, d02, b . I need to select data and order them so that values with "d" will be first and rest will be sorted alphanumerical. So the result would be d01,d02,d03,a,b

Script to create and insert data:

CREATE TABLE TestTest(
Name varchar(200)
)
DELETE FROM TestTest

INSERT INTO TestTest( Name )
VALUES( 'a' )

INSERT INTO TestTest( Name )
VALUES( 'd01');

INSERT INTO TestTest( Name )
VALUES( 'd04');

INSERT INTO TestTest( Name )
VALUES( 'd02');

INSERT INTO TestTest( Name )
VALUES( 'b' );

Thx for any help ;)

Was it helpful?

Solution

Select *
From TestTest
Order By CASE WHEN LEFT(Name,1)='d' THEN 1 ELSE 2 END,Name

SQL Fiddle Demo

OTHER TIPS

Quick soution:

Select * 
from TestTest
order by case when Name like 'd%' then 'aaaaa'+Name else Name end
select * from TestTest order by case when Name='d01' then 1
                                            when Name='d02' then 2
                                            when Name ='d04' then 3
                                            end  desc
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top