Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgresql: auto lowercase text while (or before) inserting to a column

I want to achieve case insensitive uniqueness in a varchar column. But, there is no case insensitive text data type in Postgres. Since original case of text is not important, it will be a good idea to convert all to lowercase/uppercase before inserting in a column with UNIQUE constraint. Also, it will require one INDEX for quick search.

Is there any way in Postgres to manipulate data before insertion?

I looked at this other question: How to automatically convert a MySQL column to lowercase. It suggests using triggers on insert/update to lowercase text or to use views with lowercased text. But, none of the suggested methods ensure uniqueness.

Also, since this data will be read/written by various applications, lowercasing data in every individual application is not a good idea.

like image 905
user1144616 Avatar asked Jan 28 '12 16:01

user1144616


People also ask

Is PostgreSQL case sensitive for column names?

Postgres stores unquoted column names in lowercase. The column names in a select statement are not case sensitive unless quoted.

Is Postgres column case sensitive?

So, yes, PostgreSQL column names are case-sensitive (when double-quoted): SELECT * FROM persons WHERE "first_Name" = 'xyz'; Read the manual on identifiers here. My standing advice is to use legal, lower-case names exclusively so double-quoting is not needed.

What is Citext in PostgreSQL?

The citext data type allows you to eliminate calls to lower in SQL queries, and allows a primary key to be case-insensitive. citext is locale-aware, just like text , which means that the matching of upper case and lower case characters is dependent on the rules of the database's LC_CTYPE setting.

Is Postgres order by case-insensitive?

No, these both are the same, just a different naming convention.


2 Answers

You don't need a case-insensitive data type (although there is one)

CREATE UNIQUE INDEX idx_lower_unique 
   ON your_table (lower(the_column));

That way you don't even have to mess around with the original data.

like image 113
a_horse_with_no_name Avatar answered Oct 05 '22 09:10

a_horse_with_no_name


ALTER TABLE your_table
  ADD CONSTRAINT your_table_the_column_lowercase_ck
  CHECK (the_column = lower(the_column));

From the manual:

The use of indexes to enforce unique constraints could be considered an implementation detail that should not be accessed directly.

like image 45
Craig R. Skinner Avatar answered Oct 05 '22 10:10

Craig R. Skinner