join 2 tables case sensitive upper and lower case

23,959

Solution 1

There are at least two quick ways you can solve this.

1. You specify a case-sensitive collation (rules for comparing strings across characters in a character set) for A.Code and B.Code. In MySQL and a few other database management systems, the default collation is case-insensitive.

That is, assuming that you're using MySQL or similar, you'll have to modify your statement as such:

SELECT Code, BrandName, Count(*) QTY, SUM(Price) TOTAL
FROM A
INNER JOIN B
ON A.Code=B.Code COLLATE latin1_bin
GROUP BY Code, BrandName

If, however, you plan on only performing case-sensitive queries on A and B, it may be in your interest to set the default collation on those two tables to case-sensitive.

Please see How can I make SQL case sensitive string comparison on MySQL?

2. Cast A.Code and B.Code to a binary string and compare the two. This is an simple way to compare two strings, byte-by-byte, thus achieving case-insensitivity.

SELECT Code, BrandName, Count(*) QTY, SUM(Price) TOTAL
FROM A
INNER JOIN B
ON BINARY A.Code=B.Code
GROUP BY Code, BrandName

Solution 2

Since you use a collation that is case insensitive and want to differentiate on case try using the collate keyword with a suitable case-sensitive collation:

INNER JOIN B
ON A.Code COLLATE Latin1_General_CS_AS_KS_WS  = B.Code COLLATE Latin1_General_CS_AS_KS_WS 
Share:
23,959
vovkjn
Author by

vovkjn

Updated on June 11, 2021

Comments

  • vovkjn
    vovkjn about 3 years

    I have 2 tables and need to get result on brand code.

    In the database i have for example 2 different brands but their code is the same (only difference in lower and upper case). For example:

    code Name ab Nike AB Adidas

    How to inner join 2 tables on code to get this 2 separately?

    Right now after inner join i get total sum of this 2.

    SELECT Code, BrandName, Count(*) QTY, SUM(Price) TOTAL
    FROM A
    INNER JOIN B
    ON A.Code=B.Code
    GROUP BY Code, BrandName
    

    This query will give me wrong result as it does not join sensitively on upper and lower case.

    Please help :)

  • jpw
    jpw about 9 years
    I'm not sure if you need to specify the collation on both sides of the join - it might be enough with ON A.Code = B.Code COLLATE Latin1_General_CS_AS_KS_WS
  • jpw
    jpw about 9 years
    Cool, good to know - I haven't used collate that much before.
  • Joel
    Joel about 7 years
    Changing to BINARY is actually a bad idea, as some collations will compare equal for accented characters, for instance, though the binary form would be different.