postgresql - SQL: Unique constraint when column is a certain value -
create table foo ( dt date not null, type text not null, constraint unique_dt_type unique(dt,type) -- check constraint(?) )
having brain-dud when trying think of right syntax create unique constraint when condition exists.
given, type
can have values a-f
, there can 1 a
per date, there can multiple b-f
. example of table:
2010-01-02 | 'a' -- 1 2010-01-02 | 'b' -- can have multiple 2010-01-02 | 'b' 2010-01-02 | 'b' 2010-01-02 | 'c' -- can have multiple 2013-01-02 | 'a' -- 1 2010-01-02 | 'b' -- can have multiple 2010-01-02 | 'b' 2013-01-02 | 'f' -- can have multiple 2013-01-02 | 'f'
tried reading check/unique syntax there weren't examples. check
came close limited range , wasn't used in conjunction unique
scenario. tried searching, search skills either not par, or there aren't similar questions.
postgresql can address needs via it's "partial index" feature. in practice accomplished adding clause create index statement.
sample:
create index my_partial_ix on my_sample_table (my_sample_field) not (my_sample_field = 'duplicates ok');
take here: http://www.postgresql.org/docs/current/interactive/indexes-partial.html
pay particular attention section example 11-3. setting partial unique index
. gives example lines stated objective.
Comments
Post a Comment