简体   繁体   中英

SQL Sort Order with Null values last

I have the following test-code:

CREATE TABLE #Foo (Foo int)

INSERT INTO #Foo SELECT 4
INSERT INTO #Foo SELECT NULL
INSERT INTO #Foo SELECT 2
INSERT INTO #Foo SELECT 5
INSERT INTO #Foo SELECT 1

SELECT * FROM #Foo
 ORDER BY
  CASE WHEN Foo IS NULL THEN Foo DESC ELSE Foo END

DROP TABLE #Foo

I'm trying to produce the following output:

1
2
3
4
5
NULL

"If null then put it last"

How is that done using Sql 2005

/M

One way is to sort it like this:

ORDER BY 
(CASE WHEN Foo IS NULL THEN 1 ELSE 0 END), Foo

Or: First sort by null, then sort by the Foo contents.

You can also do

SELECT * FROM #Foo ORDER BY COALESCE(Foo, 2147483647)

which will replace NULL with the largest possible int for the purposes of sorting only (so leaving the retured values alone) and so shunt it to the back of any order.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM