11

So I see this question has a good answer, but I want to round up no matter what, instead of rounding down no matter what. Adding 1 to it before casting int wouldn't work because it would "round" 5.0 into 6.0, for example.

So how should I implement ceil in SQLite?

Community
  • 1
  • 1
wrongusername
  • 18,564
  • 40
  • 130
  • 214

4 Answers4

11

How about this?

select (case when x = cast(x as int) then cast(x as int)
             else 1 + cast(x as int)
        end)
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
  • I know this was a while ago but Gordon I think DomingoR's answer is probably the most succinct here. – Bruno May 31 '17 at 07:13
  • 1
    This one (although more verbose than DomingoR's answer) is actually correct. – tonypdmtr Nov 06 '17 at 22:10
  • This one is the correct approch since it covers all the corner cases. [Here](https://stackoverflow.com/a/54399937/7594961) is a more readable version. – Bertram Gilfoyle Jun 18 '19 at 11:23
7

This will give you the same answer more elegantly:

SELECT CAST(x+1-1e-n AS INT);

(assuming you won't have a precision greater than n decimal points)

DomingoR
  • 181
  • 1
  • 9
0

using php you can easily:

$db->createFunction('ceil', 'ceil', 1);

$db->createFunction('floor', 'floor', 1);

select ceil(\`column`) from table;
Marcin Nabiałek
  • 109,655
  • 42
  • 258
  • 291
  • Agreed, this doesn't apply to pure SQLite – FinancialRadDeveloper Feb 01 '18 at 12:54
  • Although the language is php what I feel is that @user2812583 has actually proposed a valid solution. You can always create custom functions in SQLite like this but thankfully there are better approaches in this context. Still +1 from me for proposing something alternative. – Ayan Sengupta Apr 25 '18 at 05:53
-2

Some useful answers, I found this solution really easy as well.

select round(column+0.5) from table;

It will mean you are always rounding up if your original number is < 0.5 or rounding back down if your original number is > 0.5

Eric Brandt
  • 7,886
  • 3
  • 18
  • 35