SlideShare a Scribd company logo
Introduction To SQL Unit 7 Modern Business Technology Introduction To TSQL Unit 7 Developed by Michael Hotek
Integrity Integrity is the process by which data is validated and consistency is enforced Databases were designed with integrity as a primary factor Integrity can be enforced by a variety of means Rules Defaults Constraints Primary keys Foreign keys Unique indexes Triggers Integrity can also be programmatic or declarative
Declarative Integrity Defaults and constraints can be used directly in a create table statement, hence declarative integrity Constraints include Check Unique Primary Key Reference Constraints can be column or table level Defaults are only column level
Defaults A default clause is used to supply a value for a column when one is not explicitly specified in an insert statement For a DEFAULT constraint: [CONSTRAINT  constraint_name ] DEFAULT { constant _ expression  |  niladic-function  | NULL} [FOR  col_name ] create table address (CompID int not null, Address  varchar(50)  not null, City   varchar(30)  default 'Chicago' , State   char(2)  default 'IL' )
Defaults Functions can also be used in place of constants as long as they return a single value The value of the default must match the datatype of the column Character and date values must be enclosed in quotes A column can have only one default sp_helpconstraint can be used to return constraint information about a table.
Check Constraints Check constraints are used to enforce domain integrity Can be applied at a table and a column level Constraints are used to specify: List or set of values range of values Format for data Conditions on a value Enforced during inserts and updates Must evaluate to a true or false
Column Constraints create table people (SSN char(11) not null constraint chk_ssn check (SSN like '[0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9][0-9][0-9]' , FirstName varchar(30) not null, LastName varchar(50) not null, … ) or create table people (SSN char(11) not null check (SSN like '[0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9][0-9][0-9]' , FirstName varchar(30) not null, LastName varchar(50) not null, … )
Table Constraints Used for more than one column create table discounts (Type varchar(40) not null, StoreID char(4) not null, LowQty int not null, HighQty int not null, Discount float null, constraint chk_low_high check (LowQty <= HighQty) )
Indexes Separate structure attached to a table Contain pointers to the physical data Used to increase performance when: Finding rows Correlating data across tables Ordering result sets Inserting data in some cases Can enforce unique values in a column or table CREATE [UNIQUE] [CLUSTERED | NONCLUSTERED] INDEX  index_name ON [[ database . ] owner . ] table_name   ( column_name  [ ,   column_name ]... ) [WITH[FILLFACTOR  =   x ][[ , ] IGNORE_DUP_KEY] [[ , ] {SORTED_DATA  | SORTED_DATA_REORG}]  [[ , ] {IGNORE_DUP_ROW |ALLOW_DUP_ROW}]] [ON  segment_name ]
Pages Data is stored in SQL Server is a set of structures called pages Each page is 2K in size (8K in 7.0) Many rows can be on a single page A single row must be contained entirely on a page Each page contains a header area that identifies the contents of each page Pages are stored in a doubly linked list
Indexes As data gets added, a large number of pages are created Indexes were devised to quickly navigate these pages Indexes are also stored in pages  The index pages are stored in a B-Tree to support quick location of information
Indexes 177-32-1176 756-30-7391 756-30-7391 899-46-2035 177-32-1176 267-41-2394 409-56-7008 177-32-1176... 213-46-8915... 238-95-7766... 267-41-2394... 341-53-8472... 402-31-7808... 409-56-7008... 532-86-9471... 655-27-5281... 756-30-7391... 775-93-6481... 835-21-6639... Data Pages Index Pages
Indexes There are two types of indexes clustered nonclusterd Only be 1 clustered index per table Up to 249 nonclustered indexes Order of data in the table is determined by the type of index clustered index Data in the same order as the index nonclustered index Data in the order it was inserted
Keys and Indexes Keys: Logical Primary, foreign, and common Physical Single column or composite This is an index Indexes are not necessarily logical keys Indexes can be applied to columns that are not keys Can contain up to 16 columns Can have a maximum size of 256 bytes
Clustered Index Only one per table This is your most powerful index Physically orders the data in a table Can be equated to the old card catalog Good for range searches Slow for inserts page splitting
Clustered Indexes Bennet 1007 Page 1001 Karsen 1009 Smith 1062 Key ptr Karsen 1315 Page 1009 Key ptr Bennet 1132 Page 1007 Greane 1133 Hunter 1127 Key ptr Hunter Page 11127 Jenkins Greane Page 1133 Green Greene Bennet Page 1132 Chan Edwards Dull Data Pages Leaf Level Intermediate Root Page
Clustered Indexes The leaf level of the index is the data page of the table Only one entry can point to a page in the next level Require an additional 120% of space during creation
Nonclustered Indexes Data is stored in a random order at the data page level Up to 249 nonclustered indexes can be defined per table Good for searches of explicit values Are much larger than a clustered index
Nonclustered Indexes Page 1001 Bennet 1007 1421,1 Karsen 1305 1876,1 Smith 1062 1242,1 Page 1007 Bennet 1132 1421,1 Greane 1133 1242,4 Hunter 1127 1242,1 Page 1305 Karsen 1311 1876,1 Page 1133 Greane 1242,4 Green 1409,2 Greene 1421,2 Page 1127 Hunter 1242,1 Jenkins 1241,4 Page 1421 18 Bennet 19 Greene 20 Ringer Page 1409 21 Dull 22 Green 23 White Page 1241 10 O'Leary 11 Ringer 12 White 13 Jenkins Page 1242 14 Hunter 15 Smith 16 Ringer 17 Greane Page 1132 Bennet 1421,1 Chan 1129,3 Dull 1409,1 Edwards 1018,5 Key Row ptr Page ptr Key Row ptr Page ptr Key Row ptr Root Page Intermediate Leaf Pages Data Pages
Nonclustered Indexes The root and intermediate levels work similarly for both clustered and nonclustered indexes The leaf level of a nonclustered index contains a pointer to the row on each data page The pointers at the leaf level are in index order
Unique Constraint Ensures no two rows have the same value Allows one null value in a column Creates a unique, nonclustered index by default create table publishers (pub_id char(4) null, constraint  u_pub_id unique , pub_name varchar(30) not null)
Primary Key Ensures no two rows have the same value Nulls are not allowed Creates a unique, clustered index by default create table publishers (pub_id  char(4) constraint publishers_PK primary key , pub_name varchar(30)) create table sales (stor_id char(4) not null, ord_num varchar(20) not null, date datetime nit null, constraint sales_PK primary key nonclustered (stor_id, ord_num) )
Referential Integrity Used to maintain foreign keys when data is inserted or updated Column create table <table name> (column datatype [constraint  constraint_name] references ref_table [ref_column] Table [constraint  constraint_name] foreign key (column [{,column}…]) references ref_table [(column [{, column}…])]
Referential Integrity Use a column level constraint when only one column needs to be compared Use a table level constraint when more than one column needs to be compared The table in the references clause must already have a primary/unique constraint or a unique index defined on the columns A roll back is issued if referential integrity is violated and a message is sent back
Referential Integrity Column Level create table titles (title_id tid not null, title varchar(80) null, pub_id char(4) null constraint publishers_pub_id references publishers(pub_id) , notes varchar(200) null) Restrictions
Referential Integrity create table salesdetail (stor_id char(4) not null, ord_num varchar(20) not null, title_id tid not null, qty int not null, discount float not null, constraint salesdetail_FK1 foreign key (stor_id, ord_num) references sales(stor_id, ord_num), constraint salesdetail_FK2 foreign key (title_id) references titles(title_id) )
Referential Integrity When primary keys are deleted and updated, three different option could be performed: Restrict Cascade Set null Declarative RI enforces a restrict Cascade and set null can only be accomplished with triggers In a perfect world, updates to a primary key are not allowed In an imperfect world, these should be kept to a minimum
Error Messages Custom messages can be added with sp_addmessage Drop a message with sp_dropmessage Get a message with sp_getmessage In Sybase, these messages can be bound to a constraint so that on a failure, a nice message to returned to the user Bind messages using sp_bindmsg Unbind messages using sp_unbindmsg
Alter Table Once a table is created, certain modifications to its structure can be performed Allowed: Add columns Add, drop, or change constraints Not allowed Dropping columns Changing datatypes Changing width of columns Changing nullability options Constraints can only be modified with an alter table statement Modifications to constraints do not affect existing data
Alter Table ALTER TABLE [ database . [ owner ] . ] table_name   [WITH NOCHECK] [ADD { col_name column_properties  [ column_constraints ] | [[ , ]  table_constraint ]} [ ,  { next_col_name  |  next_table_constraint }]...] |  [DROP [CONSTRAINT]  constraint_name  [ ,   constraint_name2 ]...]
Getting Help To obtain information about constraints and defaults defined for a table use sp_helpconstraint table
Unit 7 Review Constraints are used to enforce integrity A default will supply a value during an insert Check constraints enforce valid data during inserts and updates Data is stored in data pages that are 2K in size A table can have 1 clustered index Physically orders the data Leaf level of index is the data pages Used for range searches A table can have up to 249 nonclusterd indexes Does not order the data The leaf level of the index contains pointers to rows Used for explicit searches Indexes can have up to 16 columns Can be a maximum of 256 bytes Unique constraint creates a unique, nonclustered index by default and allows one null Primary key constraint creates a unique, clustered index by default and doe not allow nulls
Foreign keys are enforced via a references constraint Referenced column(s) must have a primary/unique constraint or a unique index defined Roll back is performed if RI is violated The only type of RI that can be applied when modifying a primary key with constraints is restrict You can add custom messages Alter table can add columns Alter can add, drop, or modify constraints You can not drop a column You can not change a datatype You can not change the length of a column You can not change the nullability Unit 7 Review
Time allotted for exercises is 30 minutes Unit 7 Exercises

More Related Content

PPTX
DDL(Data defination Language ) Using Oracle
DOC
A must Sql notes for beginners
PPTX
SQL Commands
PPTX
DML using oracle
PPTX
SQL Server Learning Drive
PPTX
Introduction to SQL (for Chicago Booth MBA technology club)
PDF
PDF
SQL Overview
DDL(Data defination Language ) Using Oracle
A must Sql notes for beginners
SQL Commands
DML using oracle
SQL Server Learning Drive
Introduction to SQL (for Chicago Booth MBA technology club)
SQL Overview

What's hot (20)

PPTX
PPTX
Sql commands
PPTX
SQL Basics
PDF
Sql notes, sql server,sql queries,introduction of SQL, Beginner in SQL
PDF
Chapter 4 Structured Query Language
PPT
PPTX
Introduction to SQL
PPTX
DBMS information in detail || Dbms (lab) ppt
PPTX
SQL for interview
PPTX
introdution to SQL and SQL functions
PDF
Basic SQL
PPT
Introduction to-sql
PPT
Optimizing Data Accessin Sq Lserver2005
PDF
Sql ch 12 - creating database
PPTX
MySQL Essential Training
PPT
Introduction to structured query language (sql)
PPTX
DDL,DML,SQL Functions and Joins
PPTX
Sql Basics And Advanced
PDF
Database concepts
Sql commands
SQL Basics
Sql notes, sql server,sql queries,introduction of SQL, Beginner in SQL
Chapter 4 Structured Query Language
Introduction to SQL
DBMS information in detail || Dbms (lab) ppt
SQL for interview
introdution to SQL and SQL functions
Basic SQL
Introduction to-sql
Optimizing Data Accessin Sq Lserver2005
Sql ch 12 - creating database
MySQL Essential Training
Introduction to structured query language (sql)
DDL,DML,SQL Functions and Joins
Sql Basics And Advanced
Database concepts
Ad

Viewers also liked (20)

PPTX
Lalbag cha raja 1
DOCX
Progress Proposal
DOC
Arif-Resume 8+
PPTX
Google
PPTX
Integration Magic: SugarCRM and JD Edwards
DOC
Telecom
PPTX
Ferrofluid materials news
PPTX
NY Web Perf Meetup: Peeling the Web Performance Onion
DOC
Tajuk besar big
DOC
Bang tong hop_moi_truong_kd_va_ma_tran_swot_cua_viettel_1908
PPT
10 тооны бүтэц
PPTX
Мифы Древней Греции
PDF
1促進民間投資
PPSX
Homage to Sri Aurobindo
PPTX
Places in australia
PDF
цахим ном ганаа 2
PPTX
Commonwealth games 2010
DOCX
Life in the desert part 1
PPT
This is a book called dai zeer book
Lalbag cha raja 1
Progress Proposal
Arif-Resume 8+
Google
Integration Magic: SugarCRM and JD Edwards
Telecom
Ferrofluid materials news
NY Web Perf Meetup: Peeling the Web Performance Onion
Tajuk besar big
Bang tong hop_moi_truong_kd_va_ma_tran_swot_cua_viettel_1908
10 тооны бүтэц
Мифы Древней Греции
1促進民間投資
Homage to Sri Aurobindo
Places in australia
цахим ном ганаа 2
Commonwealth games 2010
Life in the desert part 1
This is a book called dai zeer book
Ad

Similar to Intro to tsql unit 7 (20)

PPTX
Sql server ___________session_15(data integrity)
PPTX
Presentation on SQL Basics to Advance in DBMS
PPT
Physical elements of data
PPTX
05 Create and Maintain Databases and Tables.pptx
PPTX
Database Overview
PPT
Introduction to sql
DOC
Adbms
PPTX
Physical Design and Development
PPT
Less08 Schema
PPT
Module02
DOC
Module 3
PPTX
ms-sql-server-150223140402-conversion-gate02.pptx
PPT
Data integrity
PPT
Review of SQL
PPT
Interactive SQL: SQL, Features of SQL, DDL & DML
DOCX
Unit-1 SQL fundamentals.docx SQL commands used to create table, insert values...
PDF
SQL -Beginner To Intermediate Level.pdf
PPTX
SQL: Data Definition Language(DDL) command
PPTX
PPTX
Database COMPLETE
Sql server ___________session_15(data integrity)
Presentation on SQL Basics to Advance in DBMS
Physical elements of data
05 Create and Maintain Databases and Tables.pptx
Database Overview
Introduction to sql
Adbms
Physical Design and Development
Less08 Schema
Module02
Module 3
ms-sql-server-150223140402-conversion-gate02.pptx
Data integrity
Review of SQL
Interactive SQL: SQL, Features of SQL, DDL & DML
Unit-1 SQL fundamentals.docx SQL commands used to create table, insert values...
SQL -Beginner To Intermediate Level.pdf
SQL: Data Definition Language(DDL) command
Database COMPLETE

More from Syed Asrarali (15)

PPT
Intro to tsql unit 14
PPT
Intro to tsql unit 15
PPT
Intro to tsql
PPT
Intro to tsql unit 13
PPT
Intro to tsql unit 12
PPT
Intro to tsql unit 10
PPT
Intro to tsql unit 9
PPT
Intro to tsql unit 8
PPT
Intro to tsql unit 6
PPT
Intro to tsql unit 5
PPT
Intro to tsql unit 4
PPT
Intro to tsql unit 3
PPT
Intro to tsql unit 2
PPT
Intro to tsql unit 1
PPT
Intro to tsql unit 11
Intro to tsql unit 14
Intro to tsql unit 15
Intro to tsql
Intro to tsql unit 13
Intro to tsql unit 12
Intro to tsql unit 10
Intro to tsql unit 9
Intro to tsql unit 8
Intro to tsql unit 6
Intro to tsql unit 5
Intro to tsql unit 4
Intro to tsql unit 3
Intro to tsql unit 2
Intro to tsql unit 1
Intro to tsql unit 11

Recently uploaded (20)

PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Machine learning based COVID-19 study performance prediction
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Encapsulation theory and applications.pdf
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PPTX
Big Data Technologies - Introduction.pptx
PDF
Empathic Computing: Creating Shared Understanding
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
Approach and Philosophy of On baking technology
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
CIFDAQ's Market Insight: SEC Turns Pro Crypto
PDF
Spectral efficient network and resource selection model in 5G networks
PPTX
A Presentation on Artificial Intelligence
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Reach Out and Touch Someone: Haptics and Empathic Computing
Machine learning based COVID-19 study performance prediction
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Encapsulation theory and applications.pdf
Building Integrated photovoltaic BIPV_UPV.pdf
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
Per capita expenditure prediction using model stacking based on satellite ima...
Big Data Technologies - Introduction.pptx
Empathic Computing: Creating Shared Understanding
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Approach and Philosophy of On baking technology
Encapsulation_ Review paper, used for researhc scholars
CIFDAQ's Market Insight: SEC Turns Pro Crypto
Spectral efficient network and resource selection model in 5G networks
A Presentation on Artificial Intelligence
The AUB Centre for AI in Media Proposal.docx
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Review of recent advances in non-invasive hemoglobin estimation
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf

Intro to tsql unit 7

  • 1. Introduction To SQL Unit 7 Modern Business Technology Introduction To TSQL Unit 7 Developed by Michael Hotek
  • 2. Integrity Integrity is the process by which data is validated and consistency is enforced Databases were designed with integrity as a primary factor Integrity can be enforced by a variety of means Rules Defaults Constraints Primary keys Foreign keys Unique indexes Triggers Integrity can also be programmatic or declarative
  • 3. Declarative Integrity Defaults and constraints can be used directly in a create table statement, hence declarative integrity Constraints include Check Unique Primary Key Reference Constraints can be column or table level Defaults are only column level
  • 4. Defaults A default clause is used to supply a value for a column when one is not explicitly specified in an insert statement For a DEFAULT constraint: [CONSTRAINT constraint_name ] DEFAULT { constant _ expression | niladic-function | NULL} [FOR col_name ] create table address (CompID int not null, Address varchar(50) not null, City varchar(30) default 'Chicago' , State char(2) default 'IL' )
  • 5. Defaults Functions can also be used in place of constants as long as they return a single value The value of the default must match the datatype of the column Character and date values must be enclosed in quotes A column can have only one default sp_helpconstraint can be used to return constraint information about a table.
  • 6. Check Constraints Check constraints are used to enforce domain integrity Can be applied at a table and a column level Constraints are used to specify: List or set of values range of values Format for data Conditions on a value Enforced during inserts and updates Must evaluate to a true or false
  • 7. Column Constraints create table people (SSN char(11) not null constraint chk_ssn check (SSN like '[0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9][0-9][0-9]' , FirstName varchar(30) not null, LastName varchar(50) not null, … ) or create table people (SSN char(11) not null check (SSN like '[0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9][0-9][0-9]' , FirstName varchar(30) not null, LastName varchar(50) not null, … )
  • 8. Table Constraints Used for more than one column create table discounts (Type varchar(40) not null, StoreID char(4) not null, LowQty int not null, HighQty int not null, Discount float null, constraint chk_low_high check (LowQty <= HighQty) )
  • 9. Indexes Separate structure attached to a table Contain pointers to the physical data Used to increase performance when: Finding rows Correlating data across tables Ordering result sets Inserting data in some cases Can enforce unique values in a column or table CREATE [UNIQUE] [CLUSTERED | NONCLUSTERED] INDEX index_name ON [[ database . ] owner . ] table_name ( column_name [ , column_name ]... ) [WITH[FILLFACTOR = x ][[ , ] IGNORE_DUP_KEY] [[ , ] {SORTED_DATA | SORTED_DATA_REORG}] [[ , ] {IGNORE_DUP_ROW |ALLOW_DUP_ROW}]] [ON segment_name ]
  • 10. Pages Data is stored in SQL Server is a set of structures called pages Each page is 2K in size (8K in 7.0) Many rows can be on a single page A single row must be contained entirely on a page Each page contains a header area that identifies the contents of each page Pages are stored in a doubly linked list
  • 11. Indexes As data gets added, a large number of pages are created Indexes were devised to quickly navigate these pages Indexes are also stored in pages The index pages are stored in a B-Tree to support quick location of information
  • 12. Indexes 177-32-1176 756-30-7391 756-30-7391 899-46-2035 177-32-1176 267-41-2394 409-56-7008 177-32-1176... 213-46-8915... 238-95-7766... 267-41-2394... 341-53-8472... 402-31-7808... 409-56-7008... 532-86-9471... 655-27-5281... 756-30-7391... 775-93-6481... 835-21-6639... Data Pages Index Pages
  • 13. Indexes There are two types of indexes clustered nonclusterd Only be 1 clustered index per table Up to 249 nonclustered indexes Order of data in the table is determined by the type of index clustered index Data in the same order as the index nonclustered index Data in the order it was inserted
  • 14. Keys and Indexes Keys: Logical Primary, foreign, and common Physical Single column or composite This is an index Indexes are not necessarily logical keys Indexes can be applied to columns that are not keys Can contain up to 16 columns Can have a maximum size of 256 bytes
  • 15. Clustered Index Only one per table This is your most powerful index Physically orders the data in a table Can be equated to the old card catalog Good for range searches Slow for inserts page splitting
  • 16. Clustered Indexes Bennet 1007 Page 1001 Karsen 1009 Smith 1062 Key ptr Karsen 1315 Page 1009 Key ptr Bennet 1132 Page 1007 Greane 1133 Hunter 1127 Key ptr Hunter Page 11127 Jenkins Greane Page 1133 Green Greene Bennet Page 1132 Chan Edwards Dull Data Pages Leaf Level Intermediate Root Page
  • 17. Clustered Indexes The leaf level of the index is the data page of the table Only one entry can point to a page in the next level Require an additional 120% of space during creation
  • 18. Nonclustered Indexes Data is stored in a random order at the data page level Up to 249 nonclustered indexes can be defined per table Good for searches of explicit values Are much larger than a clustered index
  • 19. Nonclustered Indexes Page 1001 Bennet 1007 1421,1 Karsen 1305 1876,1 Smith 1062 1242,1 Page 1007 Bennet 1132 1421,1 Greane 1133 1242,4 Hunter 1127 1242,1 Page 1305 Karsen 1311 1876,1 Page 1133 Greane 1242,4 Green 1409,2 Greene 1421,2 Page 1127 Hunter 1242,1 Jenkins 1241,4 Page 1421 18 Bennet 19 Greene 20 Ringer Page 1409 21 Dull 22 Green 23 White Page 1241 10 O'Leary 11 Ringer 12 White 13 Jenkins Page 1242 14 Hunter 15 Smith 16 Ringer 17 Greane Page 1132 Bennet 1421,1 Chan 1129,3 Dull 1409,1 Edwards 1018,5 Key Row ptr Page ptr Key Row ptr Page ptr Key Row ptr Root Page Intermediate Leaf Pages Data Pages
  • 20. Nonclustered Indexes The root and intermediate levels work similarly for both clustered and nonclustered indexes The leaf level of a nonclustered index contains a pointer to the row on each data page The pointers at the leaf level are in index order
  • 21. Unique Constraint Ensures no two rows have the same value Allows one null value in a column Creates a unique, nonclustered index by default create table publishers (pub_id char(4) null, constraint u_pub_id unique , pub_name varchar(30) not null)
  • 22. Primary Key Ensures no two rows have the same value Nulls are not allowed Creates a unique, clustered index by default create table publishers (pub_id char(4) constraint publishers_PK primary key , pub_name varchar(30)) create table sales (stor_id char(4) not null, ord_num varchar(20) not null, date datetime nit null, constraint sales_PK primary key nonclustered (stor_id, ord_num) )
  • 23. Referential Integrity Used to maintain foreign keys when data is inserted or updated Column create table <table name> (column datatype [constraint constraint_name] references ref_table [ref_column] Table [constraint constraint_name] foreign key (column [{,column}…]) references ref_table [(column [{, column}…])]
  • 24. Referential Integrity Use a column level constraint when only one column needs to be compared Use a table level constraint when more than one column needs to be compared The table in the references clause must already have a primary/unique constraint or a unique index defined on the columns A roll back is issued if referential integrity is violated and a message is sent back
  • 25. Referential Integrity Column Level create table titles (title_id tid not null, title varchar(80) null, pub_id char(4) null constraint publishers_pub_id references publishers(pub_id) , notes varchar(200) null) Restrictions
  • 26. Referential Integrity create table salesdetail (stor_id char(4) not null, ord_num varchar(20) not null, title_id tid not null, qty int not null, discount float not null, constraint salesdetail_FK1 foreign key (stor_id, ord_num) references sales(stor_id, ord_num), constraint salesdetail_FK2 foreign key (title_id) references titles(title_id) )
  • 27. Referential Integrity When primary keys are deleted and updated, three different option could be performed: Restrict Cascade Set null Declarative RI enforces a restrict Cascade and set null can only be accomplished with triggers In a perfect world, updates to a primary key are not allowed In an imperfect world, these should be kept to a minimum
  • 28. Error Messages Custom messages can be added with sp_addmessage Drop a message with sp_dropmessage Get a message with sp_getmessage In Sybase, these messages can be bound to a constraint so that on a failure, a nice message to returned to the user Bind messages using sp_bindmsg Unbind messages using sp_unbindmsg
  • 29. Alter Table Once a table is created, certain modifications to its structure can be performed Allowed: Add columns Add, drop, or change constraints Not allowed Dropping columns Changing datatypes Changing width of columns Changing nullability options Constraints can only be modified with an alter table statement Modifications to constraints do not affect existing data
  • 30. Alter Table ALTER TABLE [ database . [ owner ] . ] table_name [WITH NOCHECK] [ADD { col_name column_properties [ column_constraints ] | [[ , ] table_constraint ]} [ , { next_col_name | next_table_constraint }]...] | [DROP [CONSTRAINT] constraint_name [ , constraint_name2 ]...]
  • 31. Getting Help To obtain information about constraints and defaults defined for a table use sp_helpconstraint table
  • 32. Unit 7 Review Constraints are used to enforce integrity A default will supply a value during an insert Check constraints enforce valid data during inserts and updates Data is stored in data pages that are 2K in size A table can have 1 clustered index Physically orders the data Leaf level of index is the data pages Used for range searches A table can have up to 249 nonclusterd indexes Does not order the data The leaf level of the index contains pointers to rows Used for explicit searches Indexes can have up to 16 columns Can be a maximum of 256 bytes Unique constraint creates a unique, nonclustered index by default and allows one null Primary key constraint creates a unique, clustered index by default and doe not allow nulls
  • 33. Foreign keys are enforced via a references constraint Referenced column(s) must have a primary/unique constraint or a unique index defined Roll back is performed if RI is violated The only type of RI that can be applied when modifying a primary key with constraints is restrict You can add custom messages Alter table can add columns Alter can add, drop, or modify constraints You can not drop a column You can not change a datatype You can not change the length of a column You can not change the nullability Unit 7 Review
  • 34. Time allotted for exercises is 30 minutes Unit 7 Exercises

Editor's Notes