Skip to content

Fix SUBSTRING with a non-positive start position - #2521

Open
spokodev wants to merge 1 commit into
AlaSQL:developfrom
spokodev:fix/substring-negative-start
Open

Fix SUBSTRING with a non-positive start position#2521
spokodev wants to merge 1 commit into
AlaSQL:developfrom
spokodev:fix/substring-negative-start

Conversation

@spokodev

@spokodev spokodev commented Aug 4, 2026

Copy link
Copy Markdown

Problem

SUBSTRING / SUBSTR / MID compile SUBSTRING(str, pos, len) to str.substr(pos - 1, len). When pos is 0 or negative, pos - 1 becomes a negative index, and JavaScript's String.prototype.substr() counts a negative start from the end of the string. The result is neither correct nor consistent with any SQL dialect:

alasql("SELECT VALUE SUBSTRING('abcdef', 0, 3)")   // 'f'   (MySQL: '')
alasql("SELECT VALUE SUBSTRING('abcdef', -1, 3)")  // 'ef'  (MySQL: 'f')
alasql("SELECT VALUE SUBSTRING('abcdef', -2, 3)")  // 'def' (MySQL: 'ef')

So a computed start position that lands on 0 or goes negative silently returns wrong characters.

Fix

Follow MySQL semantics (verified against MySQL 8), which alasql already matches for positive positions:

  • start = 0 yields an empty string;
  • a negative start counts from the end (SUBSTRING('abcdef', -2) -> 'ef'), clamped to an empty string when it reaches past the beginning (SUBSTRING('abcdef', -7) -> '');
  • positive start positions are unchanged.
call before after (= MySQL 8)
SUBSTRING('abcdef', 0, 3) 'f' ''
SUBSTRING('abcdef', -1, 3) 'ef' 'f'
SUBSTRING('abcdef', -2, 3) 'def' 'ef'
SUBSTRING('abcdef', -2) 'def' 'ef'
SUBSTRING('abcdef', -7, 3) 'bcd' ''
SUBSTRING('abcdef', 2, 3) 'bcd' 'bcd'

Test

Added test/test-substring-negative-start.js. yarn test passes (2193 tests).

SUBSTRING/SUBSTR/MID compiled 'SUBSTRING(str, pos, len)' to
str.substr(pos - 1, len). When pos was 0 or negative, pos - 1 became a
negative index and JavaScript's substr() counts that from the end of the
string, so 'SUBSTRING("abcdef", 0, 3)' returned 'f' and
'SUBSTRING("abcdef", -1, 3)' returned 'ef'.

Follow MySQL semantics instead: a start of 0 yields an empty string, and
a negative start counts from the end (clamped to empty when it reaches
past the beginning). Positive start positions are unchanged.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant