fix: correct SQLite div_i formula for small dividends#5739
Closed
fix: correct SQLite div_i formula for small dividends#5739
Conversation
The ROUND(ABS(a/b) - 0.5) formula produced wrong results when |a| < |b| because SQLite integer division truncates to 0, then ROUND(-0.5) = -1. Replace with CAST(ABS(a * 1.0 / b) AS INTEGER) which forces float division and truncates correctly. Closes #5735 Co-Authored-By: Claude <noreply@anthropic.com>
prql-bot
commented
Mar 25, 2026
auto-merge was automatically disabled
March 25, 2026 09:28
Pull request was closed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problem
The SQLite
div_iimplementation usedROUND(ABS(a / b) - 0.5) * SIGN(a) * SIGN(b)to emulate floor division. When|a| < |b|, SQLite's integer/truncates to 0, soABS(0) - 0.5 = -0.5, andROUND(-0.5) = -1(SQLite rounds away from zero). This produced-1instead of the correct0.Solution
Replaced the formula with
CAST(ABS(a * 1.0 / b) AS INTEGER) * SIGN(a) * SIGN(b). The* 1.0forces float division, andCAST(... AS INTEGER)truncates toward zero — exactly the semantics needed for integer division.Testing
sqlite_div_i_small_dividend) that compiles1 // 2targeting SQLiteCloses #5735 — automated triage