MAX behavior difference with nvarchar and varchar column types

  • Hi All,

    We are getting different results for MAX function with nvarchar and varchar columns.

    create table my_table(id1 nvarchar(10), id2 varchar(10);

    insert into my_table('-1','-1);

    insert into my_table('1','1);

    select max(id1) from my_table; -> -1

    but

    select max(id2) from my_table; -> 1

    is it the default behavior? Any way to change this?

    Regards

  • Change the COLLATE for one of the columns.

    Try this:

    create table my_table(id1 nvarchar(10), id2 varchar(10))

    SELECT TABLE_NAME, COLUMN_NAME,CHARACTER_SET_NAME, COLLATION_NAME

    FROM information_schema.columns

    WHERE TABLE_NAME = 'my_table'

    insert into my_table VALUES ('-1','-1');

    insert into my_table VALUES ('1','1');

    SELECT MAX(id1 COLLATE Latin1_General_Bin2), MAX(id2)

    FROM my_table

    DROP table my_table

    You can see from the first SELECT that these columns have the same COLLATE sequence but different character sets. Changing to a binary collation resolves the issue you inquired about. Be warned that it may also cause other undesired side effects (test, test, test!).


    My mantra: No loops! No CURSORs! No RBAR! Hoo-uh![/I]

    My thought question: Have you ever been told that your query runs too fast?

    My advice:
    INDEXing a poor-performing query is like putting sugar on cat food. Yeah, it probably tastes better but are you sure you want to eat it?
    The path of least resistance can be a slippery slope. Take care that fixing your fixes of fixes doesn't snowball and end up costing you more than fixing the root cause would have in the first place.

    Need to UNPIVOT? Why not CROSS APPLY VALUES instead?[/url]
    Since random numbers are too important to be left to chance, let's generate some![/url]
    Learn to understand recursive CTEs by example.[/url]
    [url url=http://www.sqlservercentral.com/articles/St

  • Thanks very much for you answer.

Viewing 3 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic. Login to reply