Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL unique varchar case sensitivity question

I'm trying to populate a SQL table with a list of words. The table itself it pretty simple:

CREATE TABLE WORDS(   ID BIGINT AUTO_INCREMENT,    WORD VARCHAR(128) NOT NULL UNIQUE,    PRIMARY KEY(ID) ); 

The problem I'm running into is this: when I do the following inserts back to back

INSERT INTO WORDS(WORD) VALUES('Seth'); INSERT INTO WORDS(WORD) VALUES('seth'); 

The second insert fails with a constraint violation ("Duplicate entry 'seth' for key 'WORD'").

How can I get the UNIQUE constraint on WORD to be case sensitive?

like image 729
Seth Avatar asked Jun 23 '11 02:06

Seth


People also ask

Is unique in SQL case sensitive?

By default MySQL ignores differences in case and trailing spaces on varchar . If you need it to be case sensitive, you can alter the table to be varchar(...) binary .

Is varchar in SQL case sensitive?

The CHAR and VARCHAR types are not case sensitive by default, but may be declared as BINARY to make them case sensitive. ENUM , SET , and TEXT columns are not case sensitive.

Is unique key case sensitive?

MySQL is case insensitive by default and normally it is more than enough. However one of my recent projects required a case sensitive varchar column with unique index.

How do I select case sensitive in SQL?

SQL Server is, by default, case insensitive; however, it is possible to create a case-sensitive SQL Server database and even to make specific table columns case sensitive. The way to determine if a database or database object is to check its "COLLATION" property and look for "CI" or "CS" in the result.


2 Answers

Looks like mysql is case insensitive by default:

You probably need to create the column with a case sensitive collation (e.g. utf8_bin):

CREATE TABLE WORDS (     ID BIGINT AUTO_INCREMENT,      WORD VARCHAR(128) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL UNIQUE,      PRIMARY KEY(ID) ); 
like image 124
Bill Brasky Avatar answered Sep 24 '22 03:09

Bill Brasky


By default MySQL ignores differences in case and trailing spaces on varchar.

If you need it to be case sensitive, you can alter the table to be varchar(...) binary.

Use show create table to better understand how MySQL converts this to full notation.

If you need to pay attention to trailing spaces as well as be case sensitive, use varbinary instead of varchar.

like image 40
700 Software Avatar answered Sep 23 '22 03:09

700 Software