Ask the Expert

SQL CHECK constraints to validate table inserts

I have this table:

MyTable
-------
type    varchar2(20)
subtype varchar2(40)

I have various validation rules to be applied while inserting the records in this table. For example, if the type is 'Tool' the subtype can only be 'Template' or 'Document.' If the type is 'Role' the subtype can only be 'Group' or 'Individual.' How can I achieve this?

    Requires Free Membership to View

The standard SQL approach here would be the good old CHECK constraint:

create table MyTable
( type    varchar2(20)
, subtype varchar2(40)
, constraint valid_types
    check ( 
      type in ('Tool','Role') 
          )
, constraint valid_subtypes
    check ( 
      case when type = 'Tool'
            and subtype in ('Template'
                           ,'Document')
           then 1
           when type = 'Role'
            and subtype in ('Group'
                           ,'Individual')
           then 1
           else 0 end = 1
          )
)

Disclaimer: VARCHAR2 suggests that you are using Oracle. The above CHECK constraints have not been tested in Oracle. We will surely hear immediately from one of our readers if in fact Oracle does not support these constraints.

This was first published in June 2007

There are Comments. Add yours.

 
TIP: Want to include a code block in your comment? Use <pre> or <code> tags around the desired text. Ex: <code>insert code</code>

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy
Sort by: OldestNewest

Forgot Password?

No problem! Submit your e-mail address below. We'll send you an email containing your password.

Your password has been sent to: