Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server 2008 Unique Column that is Case Sensitive

Is there a way to make a column both UNIQUE and Case Sensitive?

I want to be able to put

abcde and ABCDE

in a unique column.

like image 704
Chase Florell Avatar asked Oct 03 '09 16:10

Chase Florell


People also ask

Is unique in SQL case sensitive?

UserId has data type varchar(128) and index(index_on_UserId) on a column 'UserId'. Both the above approach achieve case sensitive uniqueness and case insensitive search in MySQL.

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 make columns case sensitive in SQL Server?

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 a database or database object is by checking its “COLLATION” property and look for “CI” or “CS” in the result.

Are SQL constraints case sensitive?

The uniqueness can be enforced with a unique constraint. Whether or not the unique index is case-sensitive is defined by the server's (or the table's) collation. Here, the "CI_AS" at the end of the collation means: CI = Case Insensitive, AS = Accent sensitive. This can be changed to whatever you need it to be.


1 Answers

The uniqueness can be enforced with a unique constraint.

Whether or not the unique index is case-sensitive is defined by the server's (or the table's) collation.

You can get the current collation of your database with this query:

SELECT DATABASEPROPERTYEX('AdventureWorks', 'Collation') SQLCollation; 

and you should get something like:

SQLCollation ———————————— SQL_Latin1_General_CP1_CI_AS 

Here, the "CI_AS" at the end of the collation means: CI = Case Insensitive, AS = Accent sensitive.

This can be changed to whatever you need it to be. If your database and/or table does have a case-sensitive collation, I would expect that the uniqueness of your index will be case-sensitive as well, e.g. your abcdef and ABCDEF should be both acceptable as unique strings.

Marc

UPDATE:

I just tried this (SQL Server 2008 Developer Edition x64) - works for me (my database is generally using the "Latin1_General_CI_AS collation, but I can define a different one per table / per VARCHAR column even):

CREATE TABLE TestUnique     (string VARCHAR(50) COLLATE SQL_Latin1_General_Cp1_CS_AS)  CREATE UNIQUE INDEX UIX_Test ON dbo.TestUnique(string)  INSERT INTO dbo.TestUnique(string) VALUES ('abc') INSERT INTO dbo.TestUnique(string) VALUES ('ABC')  SELECT * FROM dbo.TestUnique 

and I get back:

string ABC abc 

and no error about the unique index being violated.

like image 152
marc_s Avatar answered Oct 02 '22 15:10

marc_s