Elad Benda
Elad Benda

Reputation: 36656

SQL: how to set precedence to a specific attribute?

I want to select all the rows of addressBook table where addresses from Paris will be first.

Can I do it with one T-SQL query ?

update: tried marc_s solution, but can I do it also when the value is an in parameter and not const 'paris' ? I get Incorrect syntax near '='

Upvotes: 0

Views: 125

Answers (2)

Alpha01
Alpha01

Reputation: 856

A couple of solutions:

  1. 2 identical selects, first with the condition address from Paris, second with the condition address not from Paris and UNION and ORDER BY

  2. in the Select statement, create an artificial column which is 0 when from Paris and 1 otherwise and ORDER BY this

  3. in the table create a new column with ordinal ordering and ORDER BY this

The solution choice depends on your needs. I would say, from the maintenance point of view, (3) is best.

Upvotes: 1

marc_s
marc_s

Reputation: 754408

Yes - sure:

SELECT  
    (some columns),
    SortOrder = CASE WHEN City = 'Paris' THEN 0 ELSE 1 END
FROM 
    dbo.addressBook
ORDER BY
    SortOrder

Upvotes: 3

Related Questions