8

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?

1
  • Yes, a partial unique index is what you need. Commented Jun 7, 2012 at 19:35

1 Answer 1

15

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Any idea why there isn't a constraint/check convention, versus using an index?
@vol7ron: probably because a constraint is (by definition) always applied to all rows in a table.
AFAIK adding any constraint would require querying table when checking for vin uniqueness. Querying table would result in index scan. You will still use an index however I think each check would cost you more points.
@a_horse_with_no_name: but the condition would apply to all rows of the table :) there can only be one unique(a,b) where b is true, which is compared to each record. Unique constraints already compare the current tuple to others, to make sure the values do not already exist, to make sure it really is unique - how this is done varies, but is probably through a hash lookup. A partial index is doing the same thing, but has one added condition

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.