Myworld
Myworld

Reputation: 1899

How to sort the fields by specific values in SQL Server 2008?

I want to select the fields from DB but I want the first fields which

Flag ='true' 

I wrote this code:

SELECT     
    ID, File, Flag
FROM  Media 
ORDER BY Flag = 'true' 

Upvotes: 0

Views: 44

Answers (3)

aweis
aweis

Reputation: 5606

You can add a fourth column that dictate an sort order!

SELECT     
    ID,
    File,
    Flag,
    CASE WHEN Flag = 'true' THEN 1
        ELSE 0
    END AS SortColumn
FROM  Media 
ORDER BY 4 DESC

Or you can divide it into two selects with an UNION between!

SELECT ID, [File], Flag FROM Media WHERE Flag = 'true'
UNION ALL
SELECT ID, [File], Flag FROM Media WHERE Flag <> 'true' OR Flag IS NULL

Upvotes: 0

Adarsh Shah
Adarsh Shah

Reputation: 6775

If it's a bit(Boolean) field then use following as you want 1(true) to appear before 0(false):

SELECT  ID, 
    File,
    Flag
 FROM  Media 
 Order by Flag DESC

If it's a string(varchar) field use following. I'm assuming you have true or false as values in the column.

SELECT  ID, 
    File,
    Flag
 FROM  Media 
 Order by Flag

Upvotes: 2

semirturgay
semirturgay

Reputation: 4201

do you mean that;select rows which have Flag="True" field in ascending order

SELECT     ID, File,Flag
           FROM  Media 
           WHERE Flag="true"
           Order by Flag ASC  

Upvotes: 0

Related Questions