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

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

Viewers also liked (19)

OpenStack Denver March Meetup - Ease Enterprise Adoption of a Private Cloud w...
OpenStack Denver March Meetup - Ease Enterprise Adoption of a Private Cloud w...OpenStack Denver March Meetup - Ease Enterprise Adoption of a Private Cloud w...
OpenStack Denver March Meetup - Ease Enterprise Adoption of a Private Cloud w...
 
01 WIKIPEDIA
01 WIKIPEDIA01 WIKIPEDIA
01 WIKIPEDIA
 
Curso: SIGA BÁSICO
Curso: SIGA BÁSICOCurso: SIGA BÁSICO
Curso: SIGA BÁSICO
 
slideshare
slideshareslideshare
slideshare
 
Sheets lesweek 6 les 6.1.gstpptx
Sheets lesweek 6 les 6.1.gstpptxSheets lesweek 6 les 6.1.gstpptx
Sheets lesweek 6 les 6.1.gstpptx
 
Prezentacja IT Kontrakt
Prezentacja IT KontraktPrezentacja IT Kontrakt
Prezentacja IT Kontrakt
 
Ejournal 9 peran dinas pendidikan untuk meningkatkan kualitas pendidikan_agus...
Ejournal 9 peran dinas pendidikan untuk meningkatkan kualitas pendidikan_agus...Ejournal 9 peran dinas pendidikan untuk meningkatkan kualitas pendidikan_agus...
Ejournal 9 peran dinas pendidikan untuk meningkatkan kualitas pendidikan_agus...
 
Stow Town Center Phase I Final Report
Stow Town Center Phase I Final ReportStow Town Center Phase I Final Report
Stow Town Center Phase I Final Report
 
Xml schema
Xml schemaXml schema
Xml schema
 
Safety.pptx 2015 8
Safety.pptx 2015 8Safety.pptx 2015 8
Safety.pptx 2015 8
 
Curso Virtual: Requisitos para trabajar en el Estado
Curso Virtual: Requisitos para trabajar en el EstadoCurso Virtual: Requisitos para trabajar en el Estado
Curso Virtual: Requisitos para trabajar en el Estado
 
Doghealthsurvey
DoghealthsurveyDoghealthsurvey
Doghealthsurvey
 
El patrocinio deportivo en la Behobia-San Sebastián: Una propuesta de valoriz...
El patrocinio deportivo en la Behobia-San Sebastián: Una propuesta de valoriz...El patrocinio deportivo en la Behobia-San Sebastián: Una propuesta de valoriz...
El patrocinio deportivo en la Behobia-San Sebastián: Una propuesta de valoriz...
 
APPSA overview
APPSA overviewAPPSA overview
APPSA overview
 
ENTREVISTAS SEMIESTRUCTURADAS REALIZADAS A MUJERES VÍCTIMAS DE VIOLENCIA, POR...
ENTREVISTAS SEMIESTRUCTURADAS REALIZADAS A MUJERES VÍCTIMAS DE VIOLENCIA, POR...ENTREVISTAS SEMIESTRUCTURADAS REALIZADAS A MUJERES VÍCTIMAS DE VIOLENCIA, POR...
ENTREVISTAS SEMIESTRUCTURADAS REALIZADAS A MUJERES VÍCTIMAS DE VIOLENCIA, POR...
 
Our life is the water
Our life is the waterOur life is the water
Our life is the water
 
Pousser les prestataires marocaines vers des acteurs logistiques mondiaux
Pousser les prestataires marocaines vers des acteurs logistiques mondiauxPousser les prestataires marocaines vers des acteurs logistiques mondiaux
Pousser les prestataires marocaines vers des acteurs logistiques mondiaux
 
Provisioning Bare Metal with OpenStack
Provisioning Bare Metal with OpenStackProvisioning Bare Metal with OpenStack
Provisioning Bare Metal with OpenStack
 
" Belle de guinee " : pomme de terre de la guinée
" Belle de guinee " : pomme de terre de la guinée" Belle de guinee " : pomme de terre de la guinée
" Belle de guinee " : pomme de terre de la guinée
 

Similar to Database constraints

Bn1037 demo oracle sql
Bn1037 demo  oracle sqlBn1037 demo  oracle sql
Bn1037 demo oracle sql
conline training
 
3. ddl create
3. ddl create3. ddl create
3. ddl create
Amrit Kaur
 
Constraints constraints of oracle data base management systems
Constraints  constraints of oracle data base management systemsConstraints  constraints of oracle data base management systems
Constraints constraints of oracle data base management systems
SHAKIR325211
 
Database constraints
Database constraintsDatabase constraints
Database constraints
Khadija Parween
 
Bn1017 a demo rdbms
Bn1017 a demo  rdbmsBn1017 a demo  rdbms
Bn1017 a demo rdbms
conline training
 
Aggregate functions in SQL.pptx
Aggregate functions in SQL.pptxAggregate functions in SQL.pptx
Aggregate functions in SQL.pptx
SherinRappai1
 
Aggregate functions in SQL.pptx
Aggregate functions in SQL.pptxAggregate functions in SQL.pptx
Aggregate functions in SQL.pptx
SherinRappai
 
Oracle SQL Fundamentals - Lecture 3
Oracle SQL Fundamentals - Lecture 3Oracle SQL Fundamentals - Lecture 3
Oracle SQL Fundamentals - Lecture 3
MuhammadWaheed44
 
Dms 22319 micro project
Dms 22319 micro projectDms 22319 micro project
Dms 22319 micro project
ARVIND SARDAR
 
Steps towards of sql server developer
Steps towards of sql server developerSteps towards of sql server developer
Steps towards of sql server developer
Ahsan Kabir
 
Intro to tsql unit 7
Intro to tsql   unit 7Intro to tsql   unit 7
Intro to tsql unit 7Syed Asrarali
 
1.Implementing_Data_Integrity.pdf
1.Implementing_Data_Integrity.pdf1.Implementing_Data_Integrity.pdf
1.Implementing_Data_Integrity.pdf
diaa46
 
SQL -Beginner To Intermediate Level.pdf
SQL -Beginner To Intermediate Level.pdfSQL -Beginner To Intermediate Level.pdf
SQL -Beginner To Intermediate Level.pdf
DraguClaudiu
 
SQL.pptx for the begineers and good know
SQL.pptx for the begineers and good knowSQL.pptx for the begineers and good know
SQL.pptx for the begineers and good know
PavithSingh
 
MS SQL Server
MS SQL ServerMS SQL Server
MS SQL Server
Md. Mahedee Hasan
 
Integrity Constraints
Integrity ConstraintsIntegrity Constraints
Integrity Constraints
madhav bansal
 
Sql commands
Sql commandsSql commands
Sql commands
Pooja Dixit
 
Check Constraints in MySQL 8.0. Presented at pre-FOSDEM MySQL Day 2020
Check Constraints in MySQL 8.0. Presented at pre-FOSDEM MySQL Day 2020Check Constraints in MySQL 8.0. Presented at pre-FOSDEM MySQL Day 2020
Check Constraints in MySQL 8.0. Presented at pre-FOSDEM MySQL Day 2020
DmitryLenev
 

Similar to Database constraints (20)

Bn1037 demo oracle sql
Bn1037 demo  oracle sqlBn1037 demo  oracle sql
Bn1037 demo oracle sql
 
Data integrity
Data integrityData integrity
Data integrity
 
3. ddl create
3. ddl create3. ddl create
3. ddl create
 
Constraints constraints of oracle data base management systems
Constraints  constraints of oracle data base management systemsConstraints  constraints of oracle data base management systems
Constraints constraints of oracle data base management systems
 
Database constraints
Database constraintsDatabase constraints
Database constraints
 
Bn1017 a demo rdbms
Bn1017 a demo  rdbmsBn1017 a demo  rdbms
Bn1017 a demo rdbms
 
Aggregate functions in SQL.pptx
Aggregate functions in SQL.pptxAggregate functions in SQL.pptx
Aggregate functions in SQL.pptx
 
Aggregate functions in SQL.pptx
Aggregate functions in SQL.pptxAggregate functions in SQL.pptx
Aggregate functions in SQL.pptx
 
Oracle SQL Fundamentals - Lecture 3
Oracle SQL Fundamentals - Lecture 3Oracle SQL Fundamentals - Lecture 3
Oracle SQL Fundamentals - Lecture 3
 
Dms 22319 micro project
Dms 22319 micro projectDms 22319 micro project
Dms 22319 micro project
 
Steps towards of sql server developer
Steps towards of sql server developerSteps towards of sql server developer
Steps towards of sql server developer
 
Intro to tsql unit 7
Intro to tsql   unit 7Intro to tsql   unit 7
Intro to tsql unit 7
 
1.Implementing_Data_Integrity.pdf
1.Implementing_Data_Integrity.pdf1.Implementing_Data_Integrity.pdf
1.Implementing_Data_Integrity.pdf
 
SQL -Beginner To Intermediate Level.pdf
SQL -Beginner To Intermediate Level.pdfSQL -Beginner To Intermediate Level.pdf
SQL -Beginner To Intermediate Level.pdf
 
SQL
SQLSQL
SQL
 
SQL.pptx for the begineers and good know
SQL.pptx for the begineers and good knowSQL.pptx for the begineers and good know
SQL.pptx for the begineers and good know
 
MS SQL Server
MS SQL ServerMS SQL Server
MS SQL Server
 
Integrity Constraints
Integrity ConstraintsIntegrity Constraints
Integrity Constraints
 
Sql commands
Sql commandsSql commands
Sql commands
 
Check Constraints in MySQL 8.0. Presented at pre-FOSDEM MySQL Day 2020
Check Constraints in MySQL 8.0. Presented at pre-FOSDEM MySQL Day 2020Check Constraints in MySQL 8.0. Presented at pre-FOSDEM MySQL Day 2020
Check Constraints in MySQL 8.0. Presented at pre-FOSDEM MySQL Day 2020
 

More from David Hoen

Computer security
Computer securityComputer security
Computer security
David Hoen
 
Introduction to prolog
Introduction to prologIntroduction to prolog
Introduction to prolog
David Hoen
 
Database introduction
Database introductionDatabase introduction
Database introduction
David Hoen
 
Building a-database
Building a-databaseBuilding a-database
Building a-database
David Hoen
 
Decision tree
Decision treeDecision tree
Decision tree
David Hoen
 
Prolog programming
Prolog programmingProlog programming
Prolog programming
David Hoen
 
Hash crypto
Hash cryptoHash crypto
Hash crypto
David Hoen
 
Introduction to security_and_crypto
Introduction to security_and_cryptoIntroduction to security_and_crypto
Introduction to security_and_crypto
David Hoen
 
Key exchange in crypto
Key exchange in cryptoKey exchange in crypto
Key exchange in crypto
David Hoen
 
Nlp naive bayes
Nlp naive bayesNlp naive bayes
Nlp naive bayes
David Hoen
 
Prolog resume
Prolog resumeProlog resume
Prolog resume
David Hoen
 
Access data connection
Access data connectionAccess data connection
Access data connection
David Hoen
 
Basic dns-mod
Basic dns-modBasic dns-mod
Basic dns-mod
David Hoen
 
Database concepts
Database conceptsDatabase concepts
Database concepts
David Hoen
 
Hashfunction
HashfunctionHashfunction
Hashfunction
David Hoen
 
Datamining with nb
Datamining with nbDatamining with nb
Datamining with nb
David Hoen
 
Text categorization as a graph
Text categorization as a graph Text categorization as a graph
Text categorization as a graph
David Hoen
 
Text classification
Text classificationText classification
Text classification
David Hoen
 
Text classification methods
Text classification methodsText classification methods
Text classification methods
David Hoen
 
Information retrieval
Information retrievalInformation retrieval
Information retrieval
David Hoen
 

More from David Hoen (20)

Computer security
Computer securityComputer security
Computer security
 
Introduction to prolog
Introduction to prologIntroduction to prolog
Introduction to prolog
 
Database introduction
Database introductionDatabase introduction
Database introduction
 
Building a-database
Building a-databaseBuilding a-database
Building a-database
 
Decision tree
Decision treeDecision tree
Decision tree
 
Prolog programming
Prolog programmingProlog programming
Prolog programming
 
Hash crypto
Hash cryptoHash crypto
Hash crypto
 
Introduction to security_and_crypto
Introduction to security_and_cryptoIntroduction to security_and_crypto
Introduction to security_and_crypto
 
Key exchange in crypto
Key exchange in cryptoKey exchange in crypto
Key exchange in crypto
 
Nlp naive bayes
Nlp naive bayesNlp naive bayes
Nlp naive bayes
 
Prolog resume
Prolog resumeProlog resume
Prolog resume
 
Access data connection
Access data connectionAccess data connection
Access data connection
 
Basic dns-mod
Basic dns-modBasic dns-mod
Basic dns-mod
 
Database concepts
Database conceptsDatabase concepts
Database concepts
 
Hashfunction
HashfunctionHashfunction
Hashfunction
 
Datamining with nb
Datamining with nbDatamining with nb
Datamining with nb
 
Text categorization as a graph
Text categorization as a graph Text categorization as a graph
Text categorization as a graph
 
Text classification
Text classificationText classification
Text classification
 
Text classification methods
Text classification methodsText classification methods
Text classification methods
 
Information retrieval
Information retrievalInformation retrieval
Information retrieval
 

Recently uploaded

The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Jeffrey Haguewood
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Ramesh Iyer
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
DianaGray10
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
g2nightmarescribd
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Product School
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Safe Software
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
Product School
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
Elena Simperl
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
DianaGray10
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 

Recently uploaded (20)

The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 

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