Given a table with a single money column how do I calculate the smallest difference between any two values in that table using TSQL? I’m looking for the performance optimized solution, which will work with millions of rows.
Given a table with a single money column how do I calculate the smallest
Share
For SQL Server 2012 you could use
This does it with one scan of the table (ideally you would have an index on
YourColumnto avoid a sort and a narrow index on that single column would reduce IO).I can’t think of a nice way of getting it to short circuit and so do less than one scan of the table if it finds the minimum possible difference of zero. Adding
MIN(CASE WHEN Diff = 0 THEN 1/0 END)to theSELECTlist and trapping the divide by zero error as a signal that zero was found would probably work but I can’t really recommend that approach…