CodePaste Logo
New Snippet New Snippet Recent Snippets Recent Snippets My Snippets My Snippets Web Code Search Snippets Search
Sign inor Register
Language: SQL

Performance of SQL’s NullIf() Function (versus Case)

593 Views
Copy Code Show/Hide Line Numbers
declare @x int, @y int, @z int
set @x = 1
set @y = 2
set @z = 1
 
-- returns @x (because not equal)
select case when @x = @y then null else @x end
 
-- returns null (because equal)
select case when @x = @z then null else @x end
 
-- ///
 
declare @x int, @y int, @z int
set @x = 1
set @y = 2
set @z = 1
 
-- returns @x (because not equal)
select NullIf(@x, @y)
 
-- returns null (because equal)
select NullIf(@x, @z)
 
-- ///
 
set nocount on
print @@version
 
declare @round int
set @round = 0
while (@round < 3)
begin
 
 set @round = @round + 1
 print ''
 print 'round ' + convert(varchar, @round)
 
 declare @l int, @w int, @x int, 
  @y int, @z int, @i int, @d datetime
 set @l = 1000000
 set @x = 1
 set @y = 2
 set @z = 1
 
 -- first, just warm up
 
 set @d = getdate()
 set @i = 0
 while (@i < @l)
 begin
  set @w = nullif(@x, @y)
  set @w = nullif(@x, @z)
  set @w = (select case 
    when @x = @y then null else @x end)
  set @w = (select case 
    when @x = @z then null else @x end)
  set @i = @i + 1
 end
 
 -- test nullif()
 
 set @d = getdate()
 set @i = 0
 while (@i < @l)
 begin
  set @w = nullif(@x, @y)
  set @w = nullif(@x, @z)
  set @i = @i + 1
 end
 print 'nullif(): ' 
  + convert(varchar, datediff(ms, @d, getdate()))
 
 -- test case when
 
 set @d = getdate()
 set @i = 0
 while (@i < @l)
 begin
  set @w = (select case 
  when @x = @y then null else @x end)
  set @w = (select case 
  when @x = @z then null else @x end)
  set @i = @i + 1
 end
 print 'case when: ' 
  + convert(varchar, datediff(ms, @d, getdate()))
 
end
 
-- ///
 
by Jerry Nixon
  March 05, 2010 @ 9:11am
Tags:

Add a comment


Report Abuse
brought to you by:
West Wind Techologies



If you find this site useful and use it frequently please consider making a donation to support this free service.
Donate