I have a situation where I want to add partial unique index in a table. This index has to be applied only to a subset of rows and rows that will be added henceforth. There are multiple databases where I have to put this index. The problem is that I have to use the data in the table of each database to determine the 'where' clause.
The following query gives an error:
create unique index user_car_unique
ON car_usage(user_id,car_id)
where date_created >
(select Max(date_created) from car_usage where id > 10)
ERROR which I get is:
ERROR: cannot use subquery in index predicate
SQL state: 0A000
Character: 98
However the following query works:
create unique index user_car_unique
ON car_usage(user_id,car_id)
where date_created > '2014-08-12'
Is there a way I can get around the "cannot use subquery in index predicate" error?
My project uses Grails. I will be writing a database migration (DBM) script to add this index which will execute during the start up time.
The reason I need this:
I have a table with duplicate entries. These entries are there because of a business requirement. To implement it I had to insert duplicates in the table. Now that requirement is changed. There should be NO duplicates in the table 'henceforth' and the old duplicates should remain as they are. To enforce that at the DB layer I want to put unique constraint. I cannot put apply constraint as there are old duplicates. Hence I opted to use partial keys. Is there any other way I can achieve this?