SQL to round up to nearest thousand

SQL expert Rudy Limeback explains how to use the CEILING function.

In SQL Server 2005, I want the next nearest thousand number. For example, if I gave 460 the output is 1000, if 1000 output 1000, if 1001 output 2000, if 1550 output 2000, if 2001 output 3000. Can you help me?
This can accomplished with the SQL Server CEILING function.

select mynumber
     , mynumber/1000.0               as dividedby1000
     , ceiling(mynumber/1000.0)      as ceilingresult
     , ceiling(mynumber/1000.0)*1000 as myfinalnumber
  from mynumbers

CEILING returns the smallest integer which is equal to or greater than the number it is given. Notice that we need a complex expression involving CEILING, in order to get the "rounded up to next 1000" number that you wanted. The "trick" (if you want to call it that) is to divide by 1000.0, which forces a decimal result, before applying the CEILING.

The query above also illustrates how to go about testing a complex expression like this. Build it up, one step at a time, in separate columns.

The results of the query on the data you provided are:

mynumber dividedby1000 ceilingresult myfinalnumber
   460      0.460000         1           1000
  1000      1.000000         1           1000
  1001      1.001000         2           2000
  1550      1.550000         2           2000
  2001      2.001000         3           3000

Neat, eh?

Dig Deeper on Oracle development languages

Data Management
Business Analytics
SearchSAP
TheServerSide.com
  • The 3 daily Scrum questions

    The 2020 Scrum Guide removed all references to the three daily Scrum questions, but does that mean you shouldn't ask them anymore?

  • Why WebAssembly? Top 11 Wasm benefits

    Latency and lag time plague web applications that run JavaScript in the browser. Here are 11 reasons why WebAssembly has the ...

  • Why Java in 2023?

    Has there ever been a better time to be a Java programmer? From new Spring releases to active JUGs, the Java platform is ...

Data Center
Content Management
HRSoftware
Close