SQL Server – How to Order Table by Two Columns

order-bysql serversql-server-2008

I would like to order this table but I can not find a way to make it work. Can you help me?

I have this table:

The table

I need this:

The other one

I have a table where documents are listed, the first field is the id of the document and the second field represents the father, so I must show a list where you can see in an orderly manner that 242 is the first document and 252 and 335 were generated from the 242.

The query:

select * from table_name order by col1 ASC, Col2 ASC

…doesn't work for me. I do this query:

SELECT
    FR1.[report_id],
    FR1.[report_parent] 
FROM [FARA_reports] FR1
WHERE
    FR1.[report_is_delete] <> 1 
    AND FR1.[report_is_tmp] <> 1
ORDER BY
    FR1.[report_id] asc, 
    FR1.[report_parent] desc

and this is my first image.

Best Answer

Another option:

select a, b
from t
order by 
    case when a < b or b is null then a else b end,
    case when a < b or b is null then b else a end ;

Test in dbfiddle.uk.