Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL: Conditional unique constraint

Tags:

postgresql

Given:

----------------------------------
      vin     | driver | is_owner
--------------+--------+----------
 231431cxzv87 | bob    | true
 231431cxzv87 | jeff   | false
 231431cxzv87 | greg   | false
 32342klj234s | jeff   | true

Is there a way to add a constraint so that there is only one owner per vin?


Edit: I found this question.
Is adding a partial unique index meant to suit this purpose?

like image 842
vol7ron Avatar asked Jun 07 '12 19:06

vol7ron


People also ask

How do I find unique constraints in PostgreSQL?

To find the name of a constraint in PostgreSQL, use the view pg_constraint in the pg_catalog schema. Join the view pg_catalog. pg_constraint with the view pg_class ( JOIN pg_class t ON t. oid = c.

What is unique constraint in PostgreSQL?

What is PostgreSQL Unique key Constraint? In PostgreSQL, the UNIQUE CONSTRAINT is used to maintain the individuality of the values that we store into a field or a column of the table. It is compatible with a group of column constraints or column constraints and a table constraint.

What is partial unique index?

A partial index is an index built over a subset of a table; the subset is defined by a conditional expression (called the predicate of the partial index). The index contains entries only for those table rows that satisfy the predicate.

What is unique index in Postgres?

PostgreSQL automatically creates a unique index when a unique constraint or primary key is defined for a table. The index covers the columns that make up the primary key or unique constraint (a multicolumn index, if appropriate), and is the mechanism that enforces the constraint.


1 Answers

Yes partial index is your choice.

create unique index unique__vin on table (vin) where is_owner;

Here index covers only rows where is_owner is true and withing this rows vin should be unique.

like image 53
kworr Avatar answered Oct 15 '22 12:10

kworr