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?
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.
Dig deeper on Oracle and SQL
Related Q&A from Rudy Limeback, SQL Consultant, r937.com
Read SQL expert Rudy Limeback's advice for counting combinations in a table with SQL's GROUP BY clausecontinue reading
Read an example of an SQL case expression from our SQL expert Rudy Limeback.continue reading
Read about the Mimer Validator, a tool used to verify your SQL code, in this tip from SQL expert Rudy Limeback.continue reading
Have a question for an expert?
Please add a title for your question
Get answers from a TechTarget expert on whatever's puzzling you.