Skip to content

MAX() on strings #609

Open
Open

Description

@mathiasrw

I have 3 questions.

Background:
At the moment MAX (and MIN but to make it easy to read I only say MAX) only works on numbers (its implemented with Math.max)

Been playing a bit with it and expanded stdlib.MAX from 55functions.js only to realise that this only works when you hardcode the values. Ups. The check needs to be in the generated code and not here - so would have to replace the existing

return 'Math.max('+Array.prototype.join.call(arguments, ',')+')'

with

return 'someAlasqlUtil.awesomeMaxFunctionThatCanHandleStrings('+Array.prototype.join.call(arguments, ',')+')'

where awesomeMaxFunctionThatCanHandleStrings would look something like

    // If all arguments are not numbers treat all as string. 
    for (var i = 0; i < arguments.length; i++) {
        if(arguments[i] != +arguments[i]){
            return Array.prototype.sort.call(arguments)[arguments.length-1] // I think I read that pop() or switch() on arguments is bad. Todo: theck if .sort() is also bad. 
        }
    };

    return Math.max.apply(null, arguments);

Questions

  1. We loose some speed if the function needs to spend time finding out if it will be comparing numbres or strings. Any inputs to weather its best to expand the existing MAX function or to make a new function falled (for example) MAX_STRING?
  2. To try to understand the code: if the MAX code was to be expanded where would the best place be to have the code from someAlasqlUtil.awesomeMaxFunctionThatCanHandleStrings ?
  3. To try to understand the code: The solution is not hard to implement with a user defined aggregation function - but if the MAX_STRING code was to be implemented in the core - where would the correct place be?
alasql.aggr.MAX_STRING = function(value,accumulator,stage){
    if(1===stage){
        return value;
    }

    if(2===stage && accumulator<value){
        return value;
    }

    return accumulator;
};

Activity

  1. agershun commented on Feb 27, 2016

    @agershun
    Member

    We can change internal aggregator implementation in 423groupby.js`` to:

                    } else if(col.aggregatorid === 'MIN') { 
    //                  return pre+'g[\''+colas+'\']=Math.min(g[\''+colas+'\'],'+colexp+');'+post; 
                        return pre+'g[\''+colas+'\']='+und(colexp,'(g[\''+colas+'\']<y?g[\''+colas+'\'],y)'+)+';'+post; 
    
                    } else if(col.aggregatorid === 'MAX') { 
    //                  return pre+'g[\''+colas+'\']=Math.max(g[\''+colas+'\'],'+colexp+');'+post; 
                        return pre+'g[\''+colas+'\']='+und(colexp,'(g[\''+colas+'\']>y?g[\''+colas+'\'],y)'+)+';'+post; 
  2. agershun commented on Feb 27, 2016

    @agershun
    Member

    In the above example I changed internal aggregator ``MAX(). We also can define this aggregator somewhere at 55functions.ja`:

    alasql.aggr.MAX_STRING = function(value,accumulator,stage){
        if(1===stage){
            return value;
        }
        if(2===stage && accumulator<value){
            return value;
        }
        return accumulator;
    };

    ... thinking...

    The important note: we have MAX() as aggregator and MAX() as function. Now aggregator is hardcoded and the function is a part of alasql.stdlib (compiled functions).

    If we want to change the aggregator we need to remove all MAX lines at 423groups.js and add custom aggregator alasql.aggr.MAX,

    To change the function we can remove it from alasql.stdlib.MAX and simply add the normal function without compilation to alasql.stdfn.MAX. In this case we do not need to dance with compilation, and AlaSQL will use just simple regular JS function.

  3. mathiasrw commented on Feb 27, 2016

    @mathiasrw
    MemberAuthor

    we have MAX() as aggregator and MAX() as function

    Interesting. So MAX(hight) ... group by xyz is a different MAX than MAX(test1, test2, test3)

    Do you have any inputs regarding peformance regarding to make a new name or expand the existing functionality?

  4. t-wy commented on Oct 2, 2025

    @t-wy

    I am not sure about the actual expected behavior of the "aggregator" MAX, and the current code (as of 2025) is as the following: (similarly for MIN) (As in src/423groupby.js)

    } else if (col.aggregatorid === 'MAX') {
    	if ('funcid' in col.expression) {
    		let colexp1 = colExpIfFunIdExists(col.expression);
    		//console.log(pre + 'if ((y=' + colexp + ") > g['" + colas + "']) g['" + colas + "'])
    		return (
    			pre +
    			`if ((g['${colas}'] == null && ${colexp1} !== null) ? y = ${colexp} : 
    				(g['${colas}'] !== null && ${colexp1} == null) ? y = g['${colas}'] : 
    				((y = ${colexp}) > g['${colas}'])) {
    				if (typeof y == 'number' || typeof y == 'bigint') {
    					g['${colas}'] = y;
    				} else if (typeof y == 'object' && y instanceof Date) {
    					g['${colas}'] = y;
    				} else if (typeof y == 'object' && typeof Number(y) == 'number') {
    					g['${colas}'] = Number(y);
    				}
    			} else if (g['${colas}'] !== null && typeof g['${colas}'] == 'object' && y instanceof Date) {
    				g['${colas}'] = g['${colas}'];
    			} else if (g['${colas}'] !== null && typeof g['${colas}'] == 'object') {
    				g['${colas}'] = Number(g['${colas}']);
    			}` +
    			post
    		);
    	}
    	return (
    		pre +
    		`if((g['${colas}'] == null && ${colexp}!== null) ? y = ${colexp} : 
    			(g['${colas}']!== null && ${colexp} == null) ? y = g['${colas}'] : 
    			((y=${colexp}) > g['${colas}'])) { 
    			if(typeof y == 'number' || typeof y == 'bigint') {
    				g['${colas}'] = y;
    			} else if(typeof y == 'object' && y instanceof Date) {
    				g['${colas}'] = y;
    			} else if(typeof y == 'object' && typeof Number(y) == 'number') {
    				g['${colas}'] = Number(y);
    			}
    		} else if(g['${colas}']!== null && typeof g['${colas}'] == 'object' && y instanceof Date) {
    			g['${colas}'] = g['${colas}'];
    		} else if(g['${colas}']!== null && typeof g['${colas}'] == 'object') {
    			g['${colas}'] = Number(g['${colas}']);
    		}` +
    		post
    	);

    So currently it seems that it still attempts to cast the value as a number if the value is in object type (not including string). I am expecting some typeof y == 'string' check would work in this case but I'm not that sure.

    Since a string does not meet all conditions, currently it is never assigned or casted to be null during execution. And this makes AlaSQL the odd one here in handling string (though it may be a compromise given that AlaSQL supports different input FROM sources and maybe if some uses numbers as strings so it may possibly break things).

    Bumping this for more attention regarding the consensus on the correct handling this basic feature when handling strings.

  5. mathiasrw commented on Nov 4, 2025

    @mathiasrw
    MemberAuthor

    @t-wy so what behaviour do you propose?

    Is it to return NULL or is to return the string latest in the alphabet? I guess NULL?

    Maybe the larges string (ascii sort) but then if there is only one (actual) number in the mix it will be the number?

  6. t-wy commented on Nov 4, 2025

    @t-wy

    @t-wy so what behaviour do you propose?

    Is it to return NULL or is to return the string latest in the alphabet? I guess NULL?

    Maybe the larges string (ascii sort) but then if there is only one (actual) number in the mix it will be the number?

    So I think the problem is that currently AlaSQL treating a numeric string as a number may lead to ambiguous behavior when the MAX aggregator follows typically SQL behaviors that support sorting by lexicographical order, and also need to keep numeric order when it only encounters number?

    Currently I have not seen any other SQL language has any function name for MAX that works for some explicit type, but I am also aware that modifying the current MAX behavior may be a breaking change.

    • If the intended behavior is to design a new MAX only for string comparison, something like MAX_STRING may be a choice.
    • Otherwise, if the behavior is to replace MAX to work for both string and number (and other type) comparison, then I would suggest it to only work when all entries are of the same string / numeric "division" (or null), or throw an error (or pick either one (e.g. the current "numeric | null" comparison) to work, assuming the result is already potentially unexpected) and request for explicit type casting function to be used. (And that can be done in one pass, but still degrades the performance.)
      • Still a tricky part: how about all numeric strings? (I would suggest using string comparison (and ask for explicit number casting if the user wants numeric comparison), but that's breaking)
    • Some other option may be to have it designed to be working like the type coercion in JS comparison when it encounters at least one non-numeric values, but the two passes needed to check for pure number beforehand may degrade the performance and the result may be unexpected, since it may make a large difference in result between 0 and 1 object of the "imposter type".
    • Or maybe the mixed comparison in current Windows File Explorer sorting (sort by the numeric prefix as number then the remainder as string) may be a choice, but I doubt it is useful for a database language.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions