Take the 2-minute tour ×
Database Administrators Stack Exchange is a question and answer site for database professionals who wish to improve their database skills and learn from others in the community. It's 100% free, no registration required.

How can I define or change a domain based on another attribute value?

F.e. domain for salary is a numeric value > 500. But if a date the person was hired > January 1st, 2013, then the salary must be > 1000.

share|improve this question
add comment

1 Answer

up vote 2 down vote accepted

I wouldn't try to solve that with a DOMAIN since that cannot reference other columns. Use a CHECK constraint instead:

ALTER TABLE foo ADD CONSTRAINT foo_min_salary
CHECK ( salary > 1000 OR hired < '2013-01-01' AND salary > 500 )
  • Define the column NOT NULL in addition to disallow NULL values.

  • Using the IS0 8601 format for the date, which is valid with any locale and the recommended form.

  • I wrote hired < '2013-01-01' on purpose, suspecting that your phrase hired > January 1st, 2013 is off by one.

  • Note how I inverted your logic to arrive at a simpler form.

  • Be aware of operator precedence. AND binds before OR.

If you are building on a domain that already demands value > 500, you can simplify the CHECK constraint to:

ALTER TABLE foo ADD CONSTRAINT foo_min_salary
CHECK ( salary > 1000 OR hired < '2013-01-01')
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.