SlideShare a Scribd company logo
Database Constraints
Database Constraints
• Database constraints are restrictions on the contents of the
database or on database operations
• Database constraints provide a way to guarantee that:
– rows in a table have valid primary or unique key values
– rows in a dependent table have valid foreign key values that reference
rows in a parent table
– individual column values are valid
Database Constraints
• SQL/400 constraints cover four specific integrity rules:
– primary key constraint (to enforce existence integrity)
– unique constraint (to enforce candidate key integrity)
– foreign key constraint (to enforce foreign key, or referential integrity)
– check constraint (to restrict a column's values; a partial enforcement of
domain integrity)
• You specify one or more of these constraints when you use the Create
Table statement to create a base table.
• You can also add or drop constraints with the Alter Table statement.
Database Constraints
• UDB/400 enforces all four types of constraints when rows in the table are
inserted or updated
• In the case of a foreign key constraint  when rows in the parent table are
updated or deleted
• Once a constraint for a table is defined
– The constraint is enforced for all database updates through any
interface
• including SQL DML, HLL built-in I/O operations, Interactive SQL (ISQL) ad
hoc updates, etc.
Create Table Sale
( OrderID Dec( 7, 0 ) Not Null
Constraint SaleOrderIdChk Check( OrderID > 0 ),
SaleDate Date Not Null,
ShipDate Date Default Null,
SaleTot Dec( 7, 2 ) Not Null,
CrdAutNbr Int Default Null,
CustID Dec( 7, 0 ) Not Null,
Primary Key( OrderID ),
Constraint SaleCrdAutNbrUK Unique ( CrdAutNbr ),
Constraint SaleCustomerFK Foreign Key ( CustID )
References Customer ( CustID )
On Delete Cascade
On Update Restrict,
Constraint SaleShipDateChk Check( ShipDate Is Null
Or ShipDate >= SaleDate ) )
Database Constraints
• If you don't specify a constraint name, UDB/400 generates a name when the
table is created.
– The constraint name can later be used in the Alter Table statement to drop the
constraint
Primary Key Constraints
• A primary key serves as the unique identifier for rows in the table.
• The syntax of the primary key constraint (following the Constraint keyword
and the constraint name, if they're specified) is
– Primary Key( column-name, ... )
– Each primary key column's definition must include Not Null.
– For a table with a primary key constraint, UDB/400 blocks any attempt to insert or
update a row that would cause two rows in the same table to have identical
value(s) for their primary key column(s).
– A table definition can have no more than one primary key constraint.
Unique Constraints
• A unique constraint is similar to a primary key constraint doesn't have to
be defined with Not Null.
• Recommend  always specify a constraint name for a unique constraint:
– Constraint constraint-name Unique ( column-name, ... )
• Note that a unique constraint does not use the Key keyword, as do primary
key and foreign key constraints.
• The SaleCrdAutNbrUK unique constraint specifies that any non-null value
for the CrdAutNbr column must be unique.
• Allowing the CrdAutNbr column to be null and specifying the
SaleCrdAutNbrUK constraint together enforce a business rule that some
orders (e.g., those paid by cash) may exist without a credit authorization
number, but any order that does have a credit authorization number must
have a unique value.
Foreign Key Constraints
• A foreign key constraint specifies how records in different tables are
related and how UDB/400 should handle row insert, delete, and update
operations that might violate the relationship.
• For example, sales rows are generally related to the customers who place
the orders. Although it might be valid for a customer row to exist without any
corresponding sale rows, it would normally be invalid for a sale row not to
have a reference to a valid customer.
• With a relational DBMS, the relationship between rows in two tables is
expressed by a foreign key in the dependent table. A foreign key is one or
more columns that contain a value identical to a primary key (or unique key)
value in some row in the parent table (i.e., the referenced table).
• With SQL/400, we might create the Customer and Sale tables so they have the
following partial constraint definitions:
– Customer table (parent)
• Primary key column: CustID
– Sale table (dependent)
• Primary key column: OrderID
• Foreign key column: CustID
• For each row in the Sale table, the CustID column should contain the same value
as the CustID column of some Customer row because this value tells which
customer placed the order.
• The purpose of specifying a foreign key constraint is to have UDB/400 ensure
that the Sale table never has a row with a (non-null) value in the CustID column
that has no matching Customer row.
Foreign Key Constraints cont.
The Sale table's foreign key constraint, which is
Constraint SaleCustomerFK Foreign Key ( CustID )
References Customer ( CustID )
On Delete Cascade
On Update Restrict
– Specifies that the CustID column in the Sale table is a foreign key that references the
CustID primary key column in the Customer table.
– UDB/400 does not allow an application to insert a new row in the Sale table unless
the row's CustID column contains the value of some existing CustID value in the
Customer table.
– Blocks any attempt to change the CustID column of a row in the Sale table to a value
that doesn't exist in any row in the Customer table. [a new or updated Sale row must
have a parent Customer row].
A foreign key constraint can specify the same table for the dependent and parent
tables. Suppose you have an Employee table with an EmpID primary key column
and a MgrEmpID column that holds the employee ID for the person's manager. :
Create Table Employee
( EmpID Dec ( 7, 0 ) Not Null,
MgrEmpID Dec ( 7, 0 ) Not Null,
other column definitions ... ,
Primary Key ( EmpID ),
Constraint EmpMgrFK Foreign Key ( MgrEmpID )
References Employee ( EmpID )
On Update Restrict
On Delete Restrict )
Check Constraints
• Used to enforce the validity of column values.
– Constraint SaleOrderIdChk Check( OrderID > 0 )
[guarantees that the OrderID primary key column is always greater than zero]
– Constraint SaleShipDateChk Check( ShipDate Is Null Or ShipDate >=
SaleDate )
[guarantees that either a row has no ship date (i.e., the ShipDate column is
null, meaning "unknown") or the ship date is on or after the sale date].
• A check constraint can compare a column to a constant (such as in the first
example), to another column in the same table (such as in the second example),
or to an expression (e.g., ColA + 3).
• UDB/400 checks to make sure a new or changed row doesn't violate any of its
table's check constraints before an insert or update operation is allowed.
check constraints cont.
You can combine check constraints for more than one column into a single
check constraint, as in the following example:
Constraint CustStatusNameChk
Check ( ( Status = 'A' Or Status = 'I' )
And ( Name <> ' ' ) )
Add/Remove Constraints
• After you create a table, you can use the Alter Table statement to
– add or remove a primary key, unique, foreign key, or check
constraint
• To drop a table's primary key constraint, just specify the Primary Key
keywords:
Alter Table Sale
Drop Primary Key
• To drop a unique, foreign key, or check constraint, you must specify the
constraint name:
Alter Table Sale
Drop Constraint SaleCustomerFK
• To add a new constraint, use the same constraint syntax as in a Create
Table statement:
Alter Table Sale
Add Constraint SaleSaleTotChk Check( SaleTot >= 0 )
Database Constraints
• Constraints can be added to a file in several ways
– the CL Add Physical File Constraint (ADDPFCST) command,
– the Create Table or Alter Table SQL statements,
– the Table Properties tab of AS/400 Operations Navigator.
• Because constraints are defined at the file level, adding one to an existing file
requires that all existing data comply with the constraint being added. You might
need to perform data cleanup prior to introducing a constraint to the file.
• If you try adding a constraint to a file already containing data that violates the
constraint, the constraint is added in a check pending status.
• A constraint having a status of check pending doesn't become enabled until after
the data in violation of the constraint is corrected and the constraint readded.
• To identify and correct the records in violation, two CL commands exist to assist
you-Work with Physical File Constraints (WRKPFCST) and Display Check
Pending Constraint (DSPCPCST).
Constraint States
• Constraints added to a file can have a state of either enabled or disabled.
• When set to disabled, the rules of the constraint are not enforced. If a
constraint is added in a check pending status, the state is automatically set
to disabled.
– An active constraint can be temporarily disabled using the State
parameter of the Change Physical File Constraint (CHGPFCST)
command.
Database Constraints
• Database constraints provide a way to guarantee that:
– rows in a table have valid primary or unique key values
– rows in a dependent table have valid foreign key values that reference
rows in a parent table
– individual column values are valid
Database Constraints
• Database constraints provide a way to guarantee that:
– rows in a table have valid primary or unique key values
– rows in a dependent table have valid foreign key values that reference
rows in a parent table
– individual column values are valid
Database constraints

More Related Content

Viewers also liked (19)

PDF
OpenStack Denver March Meetup - Ease Enterprise Adoption of a Private Cloud w...
Mike Friesenegger
 
PDF
01 WIKIPEDIA
Sierra Francisco Justo
 
PDF
Curso: SIGA BÁSICO
RC Consulting
 
PPT
slideshare
jameschloejames
 
PPTX
Sheets lesweek 6 les 6.1.gstpptx
Jos de Jong
 
PDF
Prezentacja IT Kontrakt
future3trojmiasto
 
PDF
Ejournal 9 peran dinas pendidikan untuk meningkatkan kualitas pendidikan_agus...
Mbakyu Sarah
 
PDF
Stow Town Center Phase I Final Report
Jesse Regnier
 
PPT
Xml schema
David Hoen
 
PPTX
Safety.pptx 2015 8
Todd Heuer
 
PDF
Curso Virtual: Requisitos para trabajar en el Estado
RC Consulting
 
PDF
Doghealthsurvey
Kangen Synergy Worldwide
 
PPTX
El patrocinio deportivo en la Behobia-San Sebastián: Una propuesta de valoriz...
Aitor Casal
 
PPTX
APPSA overview
randrianjafy
 
PDF
ENTREVISTAS SEMIESTRUCTURADAS REALIZADAS A MUJERES VÍCTIMAS DE VIOLENCIA, POR...
Universidad Pablo de Olavide de Sevilla (España)
 
PPSX
Our life is the water
Ali Zafar
 
PDF
Pousser les prestataires marocaines vers des acteurs logistiques mondiaux
Said ZARGUAN
 
PDF
Provisioning Bare Metal with OpenStack
Devananda Van Der Veen
 
PDF
" Belle de guinee " : pomme de terre de la guinée
Fatimata Kone
 
OpenStack Denver March Meetup - Ease Enterprise Adoption of a Private Cloud w...
Mike Friesenegger
 
Curso: SIGA BÁSICO
RC Consulting
 
slideshare
jameschloejames
 
Sheets lesweek 6 les 6.1.gstpptx
Jos de Jong
 
Prezentacja IT Kontrakt
future3trojmiasto
 
Ejournal 9 peran dinas pendidikan untuk meningkatkan kualitas pendidikan_agus...
Mbakyu Sarah
 
Stow Town Center Phase I Final Report
Jesse Regnier
 
Xml schema
David Hoen
 
Safety.pptx 2015 8
Todd Heuer
 
Curso Virtual: Requisitos para trabajar en el Estado
RC Consulting
 
Doghealthsurvey
Kangen Synergy Worldwide
 
El patrocinio deportivo en la Behobia-San Sebastián: Una propuesta de valoriz...
Aitor Casal
 
APPSA overview
randrianjafy
 
ENTREVISTAS SEMIESTRUCTURADAS REALIZADAS A MUJERES VÍCTIMAS DE VIOLENCIA, POR...
Universidad Pablo de Olavide de Sevilla (España)
 
Our life is the water
Ali Zafar
 
Pousser les prestataires marocaines vers des acteurs logistiques mondiaux
Said ZARGUAN
 
Provisioning Bare Metal with OpenStack
Devananda Van Der Veen
 
" Belle de guinee " : pomme de terre de la guinée
Fatimata Kone
 

Similar to Database constraints (20)

PPTX
Unit1_3_Database Constraints.pptx igt is about DBMS
NishthaShah16
 
PPTX
Entigrity constraint
suman kumar
 
PPTX
Sql server ___________session_15(data integrity)
Ehtisham Ali
 
PDF
03Constraints - last.pdf
ssuserfd620b
 
PPT
CSE311_IAH_Slide07_SQL Advanced Quries.ppt
noshinnawar31
 
PPTX
Database constraints
Khadija Parween
 
PPTX
data base programming chapter3 47 slides
nights1988
 
PPTX
Lecture 4 sql {basics keys and constraints}
Shubham Shukla
 
DOCX
Integrity and security
Surendra Karki Chettri
 
PDF
RDBMS Lab03 applying constraints (UIU)
Muhammad T Q Nafis
 
PPTX
CONSTRAINTS PPT.pptx
ThangaduraiA4
 
PPT
Les10
Vijay Kumar
 
PPT
Data integrity
Rahul Gupta
 
PPTX
Constraints
Abrar ali
 
PPTX
oracle Sql constraint
home
 
PPTX
apply Integrity constraints on database table
prachi gat
 
PDF
1.Implementing_Data_Integrity.pdf
diaa46
 
PDF
Bn1017 a demo rdbms
conline training
 
PPTX
Sql Constraints
I L0V3 CODING DR
 
PPTX
DBMS: Week 09 - SQL Constraints and Indexing
RashidFaridChishti
 
Unit1_3_Database Constraints.pptx igt is about DBMS
NishthaShah16
 
Entigrity constraint
suman kumar
 
Sql server ___________session_15(data integrity)
Ehtisham Ali
 
03Constraints - last.pdf
ssuserfd620b
 
CSE311_IAH_Slide07_SQL Advanced Quries.ppt
noshinnawar31
 
Database constraints
Khadija Parween
 
data base programming chapter3 47 slides
nights1988
 
Lecture 4 sql {basics keys and constraints}
Shubham Shukla
 
Integrity and security
Surendra Karki Chettri
 
RDBMS Lab03 applying constraints (UIU)
Muhammad T Q Nafis
 
CONSTRAINTS PPT.pptx
ThangaduraiA4
 
Data integrity
Rahul Gupta
 
Constraints
Abrar ali
 
oracle Sql constraint
home
 
apply Integrity constraints on database table
prachi gat
 
1.Implementing_Data_Integrity.pdf
diaa46
 
Bn1017 a demo rdbms
conline training
 
Sql Constraints
I L0V3 CODING DR
 
DBMS: Week 09 - SQL Constraints and Indexing
RashidFaridChishti
 
Ad

More from David Hoen (20)

PPT
Computer security
David Hoen
 
PPT
Introduction to prolog
David Hoen
 
PPT
Database introduction
David Hoen
 
PPTX
Building a-database
David Hoen
 
PPTX
Decision tree
David Hoen
 
PPT
Prolog programming
David Hoen
 
PPT
Hash crypto
David Hoen
 
PPTX
Introduction to security_and_crypto
David Hoen
 
PPTX
Key exchange in crypto
David Hoen
 
PPTX
Nlp naive bayes
David Hoen
 
PPT
Prolog resume
David Hoen
 
PPT
Access data connection
David Hoen
 
PPT
Basic dns-mod
David Hoen
 
PPT
Database concepts
David Hoen
 
PPTX
Hashfunction
David Hoen
 
PPTX
Datamining with nb
David Hoen
 
PDF
Text categorization as a graph
David Hoen
 
PPT
Text classification
David Hoen
 
PPT
Text classification methods
David Hoen
 
PPT
Information retrieval
David Hoen
 
Computer security
David Hoen
 
Introduction to prolog
David Hoen
 
Database introduction
David Hoen
 
Building a-database
David Hoen
 
Decision tree
David Hoen
 
Prolog programming
David Hoen
 
Hash crypto
David Hoen
 
Introduction to security_and_crypto
David Hoen
 
Key exchange in crypto
David Hoen
 
Nlp naive bayes
David Hoen
 
Prolog resume
David Hoen
 
Access data connection
David Hoen
 
Basic dns-mod
David Hoen
 
Database concepts
David Hoen
 
Hashfunction
David Hoen
 
Datamining with nb
David Hoen
 
Text categorization as a graph
David Hoen
 
Text classification
David Hoen
 
Text classification methods
David Hoen
 
Information retrieval
David Hoen
 
Ad

Recently uploaded (20)

PDF
Advancing WebDriver BiDi support in WebKit
Igalia
 
PDF
Biography of Daniel Podor.pdf
Daniel Podor
 
PDF
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
PDF
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
PDF
What Makes Contify’s News API Stand Out: Key Features at a Glance
Contify
 
PDF
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PPTX
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
PDF
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
PDF
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
PPTX
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
PDF
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
PDF
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
PDF
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PDF
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
PDF
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
PDF
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
IoT-Powered Industrial Transformation – Smart Manufacturing to Connected Heal...
Rejig Digital
 
PDF
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
Advancing WebDriver BiDi support in WebKit
Igalia
 
Biography of Daniel Podor.pdf
Daniel Podor
 
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
What Makes Contify’s News API Stand Out: Key Features at a Glance
Contify
 
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
IoT-Powered Industrial Transformation – Smart Manufacturing to Connected Heal...
Rejig Digital
 
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 

Database constraints

  • 2. Database Constraints • Database constraints are restrictions on the contents of the database or on database operations • Database constraints provide a way to guarantee that: – rows in a table have valid primary or unique key values – rows in a dependent table have valid foreign key values that reference rows in a parent table – individual column values are valid
  • 3. Database Constraints • SQL/400 constraints cover four specific integrity rules: – primary key constraint (to enforce existence integrity) – unique constraint (to enforce candidate key integrity) – foreign key constraint (to enforce foreign key, or referential integrity) – check constraint (to restrict a column's values; a partial enforcement of domain integrity) • You specify one or more of these constraints when you use the Create Table statement to create a base table. • You can also add or drop constraints with the Alter Table statement.
  • 4. Database Constraints • UDB/400 enforces all four types of constraints when rows in the table are inserted or updated • In the case of a foreign key constraint  when rows in the parent table are updated or deleted • Once a constraint for a table is defined – The constraint is enforced for all database updates through any interface • including SQL DML, HLL built-in I/O operations, Interactive SQL (ISQL) ad hoc updates, etc.
  • 5. Create Table Sale ( OrderID Dec( 7, 0 ) Not Null Constraint SaleOrderIdChk Check( OrderID > 0 ), SaleDate Date Not Null, ShipDate Date Default Null, SaleTot Dec( 7, 2 ) Not Null, CrdAutNbr Int Default Null, CustID Dec( 7, 0 ) Not Null, Primary Key( OrderID ), Constraint SaleCrdAutNbrUK Unique ( CrdAutNbr ), Constraint SaleCustomerFK Foreign Key ( CustID ) References Customer ( CustID ) On Delete Cascade On Update Restrict, Constraint SaleShipDateChk Check( ShipDate Is Null Or ShipDate >= SaleDate ) )
  • 6. Database Constraints • If you don't specify a constraint name, UDB/400 generates a name when the table is created. – The constraint name can later be used in the Alter Table statement to drop the constraint
  • 7. Primary Key Constraints • A primary key serves as the unique identifier for rows in the table. • The syntax of the primary key constraint (following the Constraint keyword and the constraint name, if they're specified) is – Primary Key( column-name, ... ) – Each primary key column's definition must include Not Null. – For a table with a primary key constraint, UDB/400 blocks any attempt to insert or update a row that would cause two rows in the same table to have identical value(s) for their primary key column(s). – A table definition can have no more than one primary key constraint.
  • 8. Unique Constraints • A unique constraint is similar to a primary key constraint doesn't have to be defined with Not Null. • Recommend  always specify a constraint name for a unique constraint: – Constraint constraint-name Unique ( column-name, ... ) • Note that a unique constraint does not use the Key keyword, as do primary key and foreign key constraints. • The SaleCrdAutNbrUK unique constraint specifies that any non-null value for the CrdAutNbr column must be unique. • Allowing the CrdAutNbr column to be null and specifying the SaleCrdAutNbrUK constraint together enforce a business rule that some orders (e.g., those paid by cash) may exist without a credit authorization number, but any order that does have a credit authorization number must have a unique value.
  • 9. Foreign Key Constraints • A foreign key constraint specifies how records in different tables are related and how UDB/400 should handle row insert, delete, and update operations that might violate the relationship. • For example, sales rows are generally related to the customers who place the orders. Although it might be valid for a customer row to exist without any corresponding sale rows, it would normally be invalid for a sale row not to have a reference to a valid customer. • With a relational DBMS, the relationship between rows in two tables is expressed by a foreign key in the dependent table. A foreign key is one or more columns that contain a value identical to a primary key (or unique key) value in some row in the parent table (i.e., the referenced table).
  • 10. • With SQL/400, we might create the Customer and Sale tables so they have the following partial constraint definitions: – Customer table (parent) • Primary key column: CustID – Sale table (dependent) • Primary key column: OrderID • Foreign key column: CustID • For each row in the Sale table, the CustID column should contain the same value as the CustID column of some Customer row because this value tells which customer placed the order. • The purpose of specifying a foreign key constraint is to have UDB/400 ensure that the Sale table never has a row with a (non-null) value in the CustID column that has no matching Customer row.
  • 11. Foreign Key Constraints cont. The Sale table's foreign key constraint, which is Constraint SaleCustomerFK Foreign Key ( CustID ) References Customer ( CustID ) On Delete Cascade On Update Restrict – Specifies that the CustID column in the Sale table is a foreign key that references the CustID primary key column in the Customer table. – UDB/400 does not allow an application to insert a new row in the Sale table unless the row's CustID column contains the value of some existing CustID value in the Customer table. – Blocks any attempt to change the CustID column of a row in the Sale table to a value that doesn't exist in any row in the Customer table. [a new or updated Sale row must have a parent Customer row].
  • 12. A foreign key constraint can specify the same table for the dependent and parent tables. Suppose you have an Employee table with an EmpID primary key column and a MgrEmpID column that holds the employee ID for the person's manager. : Create Table Employee ( EmpID Dec ( 7, 0 ) Not Null, MgrEmpID Dec ( 7, 0 ) Not Null, other column definitions ... , Primary Key ( EmpID ), Constraint EmpMgrFK Foreign Key ( MgrEmpID ) References Employee ( EmpID ) On Update Restrict On Delete Restrict )
  • 13. Check Constraints • Used to enforce the validity of column values. – Constraint SaleOrderIdChk Check( OrderID > 0 ) [guarantees that the OrderID primary key column is always greater than zero] – Constraint SaleShipDateChk Check( ShipDate Is Null Or ShipDate >= SaleDate ) [guarantees that either a row has no ship date (i.e., the ShipDate column is null, meaning "unknown") or the ship date is on or after the sale date]. • A check constraint can compare a column to a constant (such as in the first example), to another column in the same table (such as in the second example), or to an expression (e.g., ColA + 3). • UDB/400 checks to make sure a new or changed row doesn't violate any of its table's check constraints before an insert or update operation is allowed.
  • 14. check constraints cont. You can combine check constraints for more than one column into a single check constraint, as in the following example: Constraint CustStatusNameChk Check ( ( Status = 'A' Or Status = 'I' ) And ( Name <> ' ' ) )
  • 15. Add/Remove Constraints • After you create a table, you can use the Alter Table statement to – add or remove a primary key, unique, foreign key, or check constraint • To drop a table's primary key constraint, just specify the Primary Key keywords: Alter Table Sale Drop Primary Key • To drop a unique, foreign key, or check constraint, you must specify the constraint name: Alter Table Sale Drop Constraint SaleCustomerFK • To add a new constraint, use the same constraint syntax as in a Create Table statement: Alter Table Sale Add Constraint SaleSaleTotChk Check( SaleTot >= 0 )
  • 16. Database Constraints • Constraints can be added to a file in several ways – the CL Add Physical File Constraint (ADDPFCST) command, – the Create Table or Alter Table SQL statements, – the Table Properties tab of AS/400 Operations Navigator. • Because constraints are defined at the file level, adding one to an existing file requires that all existing data comply with the constraint being added. You might need to perform data cleanup prior to introducing a constraint to the file. • If you try adding a constraint to a file already containing data that violates the constraint, the constraint is added in a check pending status. • A constraint having a status of check pending doesn't become enabled until after the data in violation of the constraint is corrected and the constraint readded. • To identify and correct the records in violation, two CL commands exist to assist you-Work with Physical File Constraints (WRKPFCST) and Display Check Pending Constraint (DSPCPCST).
  • 17. Constraint States • Constraints added to a file can have a state of either enabled or disabled. • When set to disabled, the rules of the constraint are not enforced. If a constraint is added in a check pending status, the state is automatically set to disabled. – An active constraint can be temporarily disabled using the State parameter of the Change Physical File Constraint (CHGPFCST) command.
  • 18. Database Constraints • Database constraints provide a way to guarantee that: – rows in a table have valid primary or unique key values – rows in a dependent table have valid foreign key values that reference rows in a parent table – individual column values are valid
  • 19. Database Constraints • Database constraints provide a way to guarantee that: – rows in a table have valid primary or unique key values – rows in a dependent table have valid foreign key values that reference rows in a parent table – individual column values are valid