SlideShare a Scribd company logo
1 of 24
Data Definition Language:
Constraints
CIS-182
CIS-182 Constraints
Constraints
• Constraints define acceptable values
• Types of constraints
– Field: Not Null, Check, Unique, Primary Key, Foreign
Key
• These are Domain Constraints
– Table: Check, Unique, Primary Key, Foreign Key
• These are Entity Constraints
Required Fields
• Required fields must be set to NOT NULL
– Fields accept Null by default
– Null means missing, not known
StudentID CHAR(9) NOT NULL
Required and Optional Fields
Check Constraints
• Check Constraint
– Can set a range or end points
– Can specify that value must be in a list
– Can specify that data has a pattern
• Can test a column or table (row)
– Domain constraint defines what will be found in column
– Entity constraint defines what exists in a row
• A single test applied to multiple columns must
be done at the table level
– A project must have an end date after the start date
Operators
• Relational operators describe how to compare
numbers, dates
– =, >, <, <>, >=, <=
• Like compares patterns
• In tests to see if a value is in a list
• Logical
– And, Or tie together multiple tests
– Not generates the inverse
Ranges
• Typically used with numbers and dates
• Can test for a single endpoint
– GPA <= 4
– Birthday < GetDate()
• Can test for two endpoints
– Credits Between 1 and 10
– Credits >=1 And Credits <=10
Using Ranges
Comparing to List
• Can specify that a value must be found in a
group
• Different from a range!
– Being in the list of 1, 2, 3, 4, 5 is different from being
between 1 and 5
• Values separated by comma
Department IN (‘CIS’,’CS’,’CNA’)
Using a List
Pattern Matching
• Used when text data has specific characteristics
– Course number must be three numbers
– Department must be 2 or 3 letters
• Can test for letters, numbers, other characters
Pattern Matching Syntax
• Use Like
Department LIKE ‘C__’
• Can use wildcards
– Single character is _ (underscore)
– No, one or many characters is % (per cent)
• Use brackets if have options in a position
Department LIKE ‘[A-Z][A-Z][A-Z ][A-Z ]’
(Department must be at least two letters, with a letter or
space included in last two positions)
CourseNumber LIKE ‘[0-2][0-9][0-9]’
(numbers must start with 0, 1, or 2 and be three digits)
This is a single underscore
Using Patterns
Pattern for Phone includes literals (dashes)
Default Values
• Allows a standard value to be entered in a field
• Default value must satisfy data type
requirements
• Can use a literal value or result of a calculation
FirstName varchar(25) DEFAULT ‘Randy’
Using Default Values
Domain or Entity
• Most constraints can be applied to a table
– Not part of the field definition – can remove
constraint without changing field
– A constraint involving multiple columns must be
done at the table level
• Entity constraint:
– The Discount Price must be less than the Retail Price
– Describes what the row needs to be valid
• Domain Constraint
– The Retail Price must be more than zero
– Describes what the field needs to be valid
Unique Constraints
• Value entered into a field or fields must be
different for each row
– Student ID must be different for every student
– ISBN must be different for every book
StudentID CHAR(9) UNIQUE
Primary Key Constraint
• Primary key constraint provides a way to get a
single row in a table
– May be one or more fields
• If using multiple fields must be table-level
• Definition of a field can only be about that field
– Any field that is part of the primary key must have
data
StudentID char(9) NOT NULL PRIMARY KEY
ALTER TABLE Publishers
ADD CONSTRAINT pkPublishers
PRIMARY KEY (PublisherID)
Identity
• SQL Server has a method to create an
autonumber (auto-increment)
– Only 1 identity field per table
• Specify fieldname, data type, follow with
IDENTITY
– Can optionally include the SEED and INCREMENT
• Seed represents the starting value (defaults to 1)
• Increment is the value to change by (defaults to 1)
CourseID INT IDENTITY
PublisherID INT Identity(101,10) PRIMARY KEY
Foreign Key Constraint
• Value in one table must have related/associated
value in a second table
• Foreign key can be single or multiple columns
– If more than one column must be done as table-level
constraint
Foreign Key Syntax
CONSTRAINT fk_Name FOREIGN KEY (field list)
REFERENCES TableName(field list)
• First field list is about the current table (many
side)
• TableName is about the table on the one-side
• Second field list is optional if you’re referring to
a primary key of that second table
Working With Constraints
• Constraints can be named
– Makes it easier to change or remove the constraint
later
• If not named, SQL Server will create a name
– Every object needs an identifier!
Using ALTER
• ALTER is used to change an existing object
– Keeps current settings – including permissions
• DROP is used to remove an object
– can CREATE after DROPping but would need to reset
permissions
Example Constraints
• Change an existing table:
ALTER TABLE Students
CONSTRAINT ck_StudentID
CHECK (StudentID LIKE ‘875-[0-9][0-9]- [0-9][0-9][0-
9][0-9]’)
• Create a new table with constraint
CREATE TABLE Courses
(
Department VARCHAR(3)
CHECK (Department IN (‘CIS’,’CS’,’CNA’)
)

More Related Content

What's hot

What's hot (20)

Introduction to sql
Introduction to sqlIntroduction to sql
Introduction to sql
 
Joins in SQL
Joins in SQLJoins in SQL
Joins in SQL
 
Unit 2 oracle9i
Unit 2  oracle9i Unit 2  oracle9i
Unit 2 oracle9i
 
Sql joins
Sql joinsSql joins
Sql joins
 
Mysql joins
Mysql joinsMysql joins
Mysql joins
 
SQL commands
SQL commandsSQL commands
SQL commands
 
SQL Overview
SQL OverviewSQL Overview
SQL Overview
 
introdution to SQL and SQL functions
introdution to SQL and SQL functionsintrodution to SQL and SQL functions
introdution to SQL and SQL functions
 
SQL
SQLSQL
SQL
 
Sql subquery
Sql  subquerySql  subquery
Sql subquery
 
Introduction to-sql
Introduction to-sqlIntroduction to-sql
Introduction to-sql
 
SQL - DML and DDL Commands
SQL - DML and DDL CommandsSQL - DML and DDL Commands
SQL - DML and DDL Commands
 
Unit 4 plsql
Unit 4  plsqlUnit 4  plsql
Unit 4 plsql
 
Trigger in mysql
Trigger in mysqlTrigger in mysql
Trigger in mysql
 
Aggregate function
Aggregate functionAggregate function
Aggregate function
 
advanced sql(database)
advanced sql(database)advanced sql(database)
advanced sql(database)
 
Including Constraints -Oracle Data base
Including Constraints -Oracle Data base Including Constraints -Oracle Data base
Including Constraints -Oracle Data base
 
Sql clauses by Manan Pasricha
Sql clauses by Manan PasrichaSql clauses by Manan Pasricha
Sql clauses by Manan Pasricha
 
Introduction to structured query language (sql)
Introduction to structured query language (sql)Introduction to structured query language (sql)
Introduction to structured query language (sql)
 
MySQL Data types
MySQL Data typesMySQL Data types
MySQL Data types
 

Similar to SQL Constraints

ds 1 Introduction to Data Structures.ppt
ds 1 Introduction to Data Structures.pptds 1 Introduction to Data Structures.ppt
ds 1 Introduction to Data Structures.ppt
AlliVinay1
 

Similar to SQL Constraints (20)

OracleSQLraining.pptx
OracleSQLraining.pptxOracleSQLraining.pptx
OracleSQLraining.pptx
 
Create table
Create tableCreate table
Create table
 
15 wordprocessing ml subject - fields and hyperlinks
15   wordprocessing ml subject - fields and hyperlinks15   wordprocessing ml subject - fields and hyperlinks
15 wordprocessing ml subject - fields and hyperlinks
 
Tech Jam 01 - Database Querying
Tech Jam 01 - Database QueryingTech Jam 01 - Database Querying
Tech Jam 01 - Database Querying
 
2018 02 20_biological_databases_part2_v_upload
2018 02 20_biological_databases_part2_v_upload2018 02 20_biological_databases_part2_v_upload
2018 02 20_biological_databases_part2_v_upload
 
Relational_Model.ppt
Relational_Model.pptRelational_Model.ppt
Relational_Model.ppt
 
DBMS.pptx
DBMS.pptxDBMS.pptx
DBMS.pptx
 
ExcelTipsAndTricks.pptx
ExcelTipsAndTricks.pptxExcelTipsAndTricks.pptx
ExcelTipsAndTricks.pptx
 
ADBMS - Joins , Sorting , Distributed Database Systems
ADBMS - Joins , Sorting , Distributed Database SystemsADBMS - Joins , Sorting , Distributed Database Systems
ADBMS - Joins , Sorting , Distributed Database Systems
 
MS SQL Server
MS SQL ServerMS SQL Server
MS SQL Server
 
Unit 5 composite datatypes
Unit 5  composite datatypesUnit 5  composite datatypes
Unit 5 composite datatypes
 
lec02-data-models-sql-basics.pptx
lec02-data-models-sql-basics.pptxlec02-data-models-sql-basics.pptx
lec02-data-models-sql-basics.pptx
 
ds 1 Introduction to Data Structures.ppt
ds 1 Introduction to Data Structures.pptds 1 Introduction to Data Structures.ppt
ds 1 Introduction to Data Structures.ppt
 
Ms sql-server
Ms sql-serverMs sql-server
Ms sql-server
 
Data Base Management System.pdf
Data Base Management System.pdfData Base Management System.pdf
Data Base Management System.pdf
 
CIS110 Computer Programming Design Chapter (14)
CIS110 Computer Programming Design Chapter  (14)CIS110 Computer Programming Design Chapter  (14)
CIS110 Computer Programming Design Chapter (14)
 
1.1 introduction to Data Structures.ppt
1.1 introduction to Data Structures.ppt1.1 introduction to Data Structures.ppt
1.1 introduction to Data Structures.ppt
 
Oracle Sql & PLSQL Complete guide
Oracle Sql & PLSQL Complete guideOracle Sql & PLSQL Complete guide
Oracle Sql & PLSQL Complete guide
 
SQL.ppt
SQL.pptSQL.ppt
SQL.ppt
 
ADBMS Unit-II b
ADBMS Unit-II bADBMS Unit-II b
ADBMS Unit-II b
 

More from Randy Riness @ South Puget Sound Community College

More from Randy Riness @ South Puget Sound Community College (20)

Stored procedures
Stored proceduresStored procedures
Stored procedures
 
3 sql overview
3 sql overview3 sql overview
3 sql overview
 
Normalization
NormalizationNormalization
Normalization
 
CIS160 final review
CIS160 final reviewCIS160 final review
CIS160 final review
 
CIS 245 Final Review
CIS 245 Final ReviewCIS 245 Final Review
CIS 245 Final Review
 
CIS145 Final Review
CIS145 Final ReviewCIS145 Final Review
CIS145 Final Review
 
Cis166 Final Review C#
Cis166 Final Review C#Cis166 Final Review C#
Cis166 Final Review C#
 
Classes and Objects
Classes and ObjectsClasses and Objects
Classes and Objects
 
CIS245 sql
CIS245 sqlCIS245 sql
CIS245 sql
 
Cis245 Midterm Review
Cis245 Midterm ReviewCis245 Midterm Review
Cis245 Midterm Review
 
CSS
CSSCSS
CSS
 
XPath
XPathXPath
XPath
 
XSLT Overview
XSLT OverviewXSLT Overview
XSLT Overview
 
Views
ViewsViews
Views
 
CIS282 Midterm review
CIS282 Midterm reviewCIS282 Midterm review
CIS282 Midterm review
 
Schemas 2 - Restricting Values
Schemas 2 - Restricting ValuesSchemas 2 - Restricting Values
Schemas 2 - Restricting Values
 
CIS 145 test 1 review
CIS 145 test 1 reviewCIS 145 test 1 review
CIS 145 test 1 review
 
XML schemas
XML schemasXML schemas
XML schemas
 
Document type definitions part 2
Document type definitions part 2Document type definitions part 2
Document type definitions part 2
 
Document type definitions part 1
Document type definitions part 1Document type definitions part 1
Document type definitions part 1
 

Recently uploaded

Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
Chris Hunter
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
negromaestrong
 

Recently uploaded (20)

Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 

SQL Constraints

  • 2. Constraints • Constraints define acceptable values • Types of constraints – Field: Not Null, Check, Unique, Primary Key, Foreign Key • These are Domain Constraints – Table: Check, Unique, Primary Key, Foreign Key • These are Entity Constraints
  • 3. Required Fields • Required fields must be set to NOT NULL – Fields accept Null by default – Null means missing, not known StudentID CHAR(9) NOT NULL
  • 5. Check Constraints • Check Constraint – Can set a range or end points – Can specify that value must be in a list – Can specify that data has a pattern • Can test a column or table (row) – Domain constraint defines what will be found in column – Entity constraint defines what exists in a row • A single test applied to multiple columns must be done at the table level – A project must have an end date after the start date
  • 6. Operators • Relational operators describe how to compare numbers, dates – =, >, <, <>, >=, <= • Like compares patterns • In tests to see if a value is in a list • Logical – And, Or tie together multiple tests – Not generates the inverse
  • 7. Ranges • Typically used with numbers and dates • Can test for a single endpoint – GPA <= 4 – Birthday < GetDate() • Can test for two endpoints – Credits Between 1 and 10 – Credits >=1 And Credits <=10
  • 9. Comparing to List • Can specify that a value must be found in a group • Different from a range! – Being in the list of 1, 2, 3, 4, 5 is different from being between 1 and 5 • Values separated by comma Department IN (‘CIS’,’CS’,’CNA’)
  • 11. Pattern Matching • Used when text data has specific characteristics – Course number must be three numbers – Department must be 2 or 3 letters • Can test for letters, numbers, other characters
  • 12. Pattern Matching Syntax • Use Like Department LIKE ‘C__’ • Can use wildcards – Single character is _ (underscore) – No, one or many characters is % (per cent) • Use brackets if have options in a position Department LIKE ‘[A-Z][A-Z][A-Z ][A-Z ]’ (Department must be at least two letters, with a letter or space included in last two positions) CourseNumber LIKE ‘[0-2][0-9][0-9]’ (numbers must start with 0, 1, or 2 and be three digits) This is a single underscore
  • 13. Using Patterns Pattern for Phone includes literals (dashes)
  • 14. Default Values • Allows a standard value to be entered in a field • Default value must satisfy data type requirements • Can use a literal value or result of a calculation FirstName varchar(25) DEFAULT ‘Randy’
  • 16. Domain or Entity • Most constraints can be applied to a table – Not part of the field definition – can remove constraint without changing field – A constraint involving multiple columns must be done at the table level • Entity constraint: – The Discount Price must be less than the Retail Price – Describes what the row needs to be valid • Domain Constraint – The Retail Price must be more than zero – Describes what the field needs to be valid
  • 17. Unique Constraints • Value entered into a field or fields must be different for each row – Student ID must be different for every student – ISBN must be different for every book StudentID CHAR(9) UNIQUE
  • 18. Primary Key Constraint • Primary key constraint provides a way to get a single row in a table – May be one or more fields • If using multiple fields must be table-level • Definition of a field can only be about that field – Any field that is part of the primary key must have data StudentID char(9) NOT NULL PRIMARY KEY ALTER TABLE Publishers ADD CONSTRAINT pkPublishers PRIMARY KEY (PublisherID)
  • 19. Identity • SQL Server has a method to create an autonumber (auto-increment) – Only 1 identity field per table • Specify fieldname, data type, follow with IDENTITY – Can optionally include the SEED and INCREMENT • Seed represents the starting value (defaults to 1) • Increment is the value to change by (defaults to 1) CourseID INT IDENTITY PublisherID INT Identity(101,10) PRIMARY KEY
  • 20. Foreign Key Constraint • Value in one table must have related/associated value in a second table • Foreign key can be single or multiple columns – If more than one column must be done as table-level constraint
  • 21. Foreign Key Syntax CONSTRAINT fk_Name FOREIGN KEY (field list) REFERENCES TableName(field list) • First field list is about the current table (many side) • TableName is about the table on the one-side • Second field list is optional if you’re referring to a primary key of that second table
  • 22. Working With Constraints • Constraints can be named – Makes it easier to change or remove the constraint later • If not named, SQL Server will create a name – Every object needs an identifier!
  • 23. Using ALTER • ALTER is used to change an existing object – Keeps current settings – including permissions • DROP is used to remove an object – can CREATE after DROPping but would need to reset permissions
  • 24. Example Constraints • Change an existing table: ALTER TABLE Students CONSTRAINT ck_StudentID CHECK (StudentID LIKE ‘875-[0-9][0-9]- [0-9][0-9][0- 9][0-9]’) • Create a new table with constraint CREATE TABLE Courses ( Department VARCHAR(3) CHECK (Department IN (‘CIS’,’CS’,’CNA’) )