SQL Server Order by Nulls alphabetically then Not Nulls

l7wslrjt  于 2023-11-16  发布在  其他
关注(0)|答案(1)|浏览(106)

I have a dataset where I'm trying to sort by having null startdate values first, then by lastname. Then nonnull startdates, also by last name:

declare @t table
  (lastname varchar(100),
  firstname varchar(50),
  startdate date)

  insert into @t
  values('Smith', 'John', '01/01/2023'),
  ('Marshall', 'Tom', NULL),
  ('Thomas', 'Frank', '01/01/2022'),
  ('Schmidt', 'Mike', NULL),
  ('Carter', 'Gary', '03/01/2023'),
  ('Belle', 'Albert', NULL)

  LastName     FirstName       StartDate
 Smith         John               2023-01-01
 Marshall      Tom               NULL
 Thomas        Frank             2022-01-01
 Schmidt       Mike              NULL
 Carter        Gary             2023-03-01
 Belle         Albert           NULL

Desired Output:

LastName     FirstName        StartDate
   Belle         Albert           NULL
   Marshall       Tom             NULL
   Schmidt        Mike            NULL
   Carter        Gary             2023-03-01
   Smith         John             2023-01-01
   Thomas        Frank            2022-01-01

I've tried doing a Union:

select * 
  into #nulls
  from @t
  where startdate is null
  order by lastname

  select * 
  into #nonnulls
  from @t
  where startdate is not null
  order by lastname

  select *
  from #nulls
  UNION
  select *
  from #nonnulls

I've also tried using Order by Case:

select *
  from @t
  order by case when startdate is null then lastname 
                when startdate is not null then lastname end
7fhtutme

7fhtutme1#

A more efficient version of the ORDER BY CASE is to use UNION ALL to combine the two halves, and sort it using an ordering column

SELECT *, 1 AS ordering
FROM @t
WHERE startdate IS NULL

UNION ALL

SELECT *, 2
FROM @t
WHERE startdate IS NOT NULL

ORDER BY
  ordering,
  lastname

This allows the server to use a Merge Concatenation rather than a Sort.

相关问题