Question

How can I create a case insensitive index or constraint in HSQL running in PostgreSQL (;sql.syntax_pgs=true) mode?

In Postgres, it can be done with lower() or lcase():

CREATE UNIQUE INDEX lower_username_index ON enduser_table ((lcase(name)));

PostgreSQL also has the CITEXT datatype, but unfortunately it does not seem to be supported in HSQL.

I'm currently at HSQL 2.2.8 and PostgreSQL 9.0.5. Alternatively, other in-memory databases that might be a better fit for testing PostgreSQL DDL and SQL?

Thanks in advance!

Was it helpful?

Solution

With HSQLDB, it's better to define a UNIQUE constraint, rather than a unique index.

There are two ways of achieving your aim:

  1. Change the type of the column to VARCHAR_IGNORECASE, then use ALTER TABLE enduser_table ADD CONSTRAINT CONST_1 UNIQUE(name)

  2. Alternatively, create a generated column then create the UNIQUE constraint on this column. `ALTER TABLE enduser_table ADD COLUMN lc_name VARCHAR(1000) GENERATED ALWAYS AS (LCASE(name))'

With both methods, duplicate values in the NAME column are rejected. With the first method, the index is used for searches on the NAME column. With the second method, the index is used for searches on the lc_name column.

(UPDATE) If you want to use the PosgreSQL CITEXT type, define the type in HSQLDB, then use the first alternative.

CREATE TYPE CITEXT AS VARCHAR_IGNORECASE(2000)
CREATE TABLE enduser_table (name CITEXT, ...
ALTER TABLE enduser_table ADD CONSTRAINT CONST_1 UNIQUE(name)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top