Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move one exact row to top of all rows leaving all other ASCENDING

Tags:

sql

sql-server

Hello I wonder how can it be done in SQL server.

My code doesn't work.

SELECT * FROM
TABLE_NAME
WHERE NAME = 'United Kingdom'
ORDER BY Name

Here is the sample:

enter image description here

And here is expected result:

enter image description here

Thank you for your help.

like image 840
Raimonds Plume Avatar asked Apr 08 '16 10:04

Raimonds Plume


People also ask

How do you keep records on top when ordering data?

Answer: In Order by clause you can use a number which will indicate the ordinal position of the column name used in the select statement. For example Order by 2 means order by the second column values specified in the SELECT statement.

How do I SELECT a specific rank in SQL?

The RANK() function is a window function could be used in SQL Server to calculate a rank for each row within a partition of a result set. The same rank is assigned to the rows in a partition which have the same values. The rank of the first row is 1.

How do you SELECT Top 3 rank in SQL?

SELECT name, value, rn FROM ( SELECT name, value, ROW_NUMBER() OVER (PARTITION BY name ORDER BY value DESC ) AS rn FROM t ) tmp WHERE rn <= 3 ORDER BY name, rn ; Tested in: Postgres.


1 Answers

Use a case in the order by:

SELECT *
FROM TABLE_NAME
ORDER BY (CASE WHEN NAME = 'United Kingdom' THEN 1 ELSE 2 END), Name;

ORDER BY accepts multiple keys. The first puts the desired values first.

like image 197
Gordon Linoff Avatar answered Sep 25 '22 02:09

Gordon Linoff