SlideShare une entreprise Scribd logo
1  sur  33
Rushdi Shams, Dept of CSE, KUET 1
Database SystemsDatabase Systems
Understanding KeysUnderstanding Keys
Entity IntegrityEntity Integrity
Referential IntegrityReferential Integrity
Propagation ConstraintPropagation Constraint
Version 1.0Version 1.0
2Rushdi Shams, Dept of CSE, KUET
What is keyWhat is key
 A key is a CONSTRAINT in field/ column in aA key is a CONSTRAINT in field/ column in a
tabletable
 Generally, keys are essential in database systemsGenerally, keys are essential in database systems
to invoke some integrityto invoke some integrity
 By a key, you can tag a field in a table so that theBy a key, you can tag a field in a table so that the
field can be used to relate tablesfield can be used to relate tables
3Rushdi Shams, Dept of CSE, KUET
Types of keyTypes of key
There are 3 types of keys in general. They are-There are 3 types of keys in general. They are-
 Primary keyPrimary key
 Unique keyUnique key
 Foreign keyForeign key
4Rushdi Shams, Dept of CSE, KUET
Primary keyPrimary key
 Used to uniquely identify a row in a tableUsed to uniquely identify a row in a table
 Also calledAlso called Surrogate keySurrogate key
 Say, you have a table of names of the students ofSay, you have a table of names of the students of
your class and their ages. How can you differyour class and their ages. How can you differ
between them? Because many of you have thebetween them? Because many of you have the
same name! don’t you? So, what happens if yousame name! don’t you? So, what happens if you
try to find out a name “Rezwana” and you findtry to find out a name “Rezwana” and you find
there are 5 Rezwanas in the class?there are 5 Rezwanas in the class?
 That invokes the idea of primary keyThat invokes the idea of primary key
5Rushdi Shams, Dept of CSE, KUET
Primary key (continued)Primary key (continued)
 This problem won’t be serious if you had anyThis problem won’t be serious if you had any
identifying criteria to differ between 5 Rezwanas.identifying criteria to differ between 5 Rezwanas.
 You still can identify 5 Rezwanas by adding anYou still can identify 5 Rezwanas by adding an
extra column in that table. Can you say whatextra column in that table. Can you say what
field that might be?field that might be?
 That is your roll number! So, 5 Rezwanas can beThat is your roll number! So, 5 Rezwanas can be
easily identifed by their roll numbers.easily identifed by their roll numbers.
 So, roll number is the primary key here.So, roll number is the primary key here.
6Rushdi Shams, Dept of CSE, KUET
Primary key (continued)Primary key (continued)
7Rushdi Shams, Dept of CSE, KUET
Primary key (continued)Primary key (continued)
8Rushdi Shams, Dept of CSE, KUET
Unique KeyUnique Key
 Unique keys are applied on the column of aUnique keys are applied on the column of a
tabletable
 Any field that is UNIQUE key, you will have toAny field that is UNIQUE key, you will have to
remember that no 2 entries in that column inremember that no 2 entries in that column in
that table will be the samethat table will be the same
 So, are you thinking “why there are primary keysSo, are you thinking “why there are primary keys
and unique keys? They are same, no?”and unique keys? They are same, no?”
9Rushdi Shams, Dept of CSE, KUET
Unique key (continued)Unique key (continued)
 No, they are not the same. In real life, when you areNo, they are not the same. In real life, when you are
creating tables, you sometimes will not want to let thecreating tables, you sometimes will not want to let the
table have the same entry twice (even though that is nottable have the same entry twice (even though that is not
the primary key)the primary key)
 An example can be, if you have a course table withAn example can be, if you have a course table with
primary key COURSE ID and another field COURSEprimary key COURSE ID and another field COURSE
NAME- take a look! You will not allow the data entryNAME- take a look! You will not allow the data entry
operator to entry the same subject name twice, do you?operator to entry the same subject name twice, do you?
 So, making COURSE NAME as UNIQUE will giveSo, making COURSE NAME as UNIQUE will give
you that opportunityyou that opportunity
10Rushdi Shams, Dept of CSE, KUET
Foreign KeyForeign Key
 Foreign keys are copies of primary key in theForeign keys are copies of primary key in the
child tablechild table
 When two tables are in relation, then child tableWhen two tables are in relation, then child table
is that table which depends on the other.is that table which depends on the other.
11Rushdi Shams, Dept of CSE, KUET
Foreign key (continued)Foreign key (continued)
12Rushdi Shams, Dept of CSE, KUET
Creating Primary keysCreating Primary keys
CREATE TABLE student(CREATE TABLE student(
student_idstudent_id number(10)number(10) NOT NULLNOT NULL,,
student_namestudent_name varchar(20),varchar(20),
PRIMARY KEY(student_id)PRIMARY KEY(student_id)
););
13Rushdi Shams, Dept of CSE, KUET
Creating Unique keysCreating Unique keys
CREATE TABLE course(CREATE TABLE course(
course_idcourse_id varchar(10)varchar(10) NOT NULL,NOT NULL,
course_namecourse_name varchar(20)varchar(20) UNIQUEUNIQUE,,
PRIMARY KEY(course_id)PRIMARY KEY(course_id)
););
14Rushdi Shams, Dept of CSE, KUET
Creating Foreign keysCreating Foreign keys
CREATE TABLE address(CREATE TABLE address(
student_idstudent_idnumber(10)number(10) NOT NULL,NOT NULL,
student_addressstudent_address varchar(30),varchar(30),
postcodepostcode varchar(10),varchar(10),
PRIMARY KEY (student_id),PRIMARY KEY (student_id),
FOREIGN KEY(student_id) REFERENCES studentFOREIGN KEY(student_id) REFERENCES student
););
BackBack
15Rushdi Shams, Dept of CSE, KUET
Case StudyCase Study
16Rushdi Shams, Dept of CSE, KUET
Case study (continued)Case study (continued)
17Rushdi Shams, Dept of CSE, KUET
Case study (continued)Case study (continued)
CREATE TABLE Band(CREATE TABLE Band(
band_idband_id varchar(10)varchar(10)
NOT NULL,NOT NULL,
band_nameband_name char(20),char(20),
PRIMARY KEY(band_id)PRIMARY KEY(band_id)
););
CREATE TABLE Track(CREATE TABLE Track(
track_idtrack_id varchar(10)varchar(10)
NOT NULL,NOT NULL,
band_idband_id varchar(10),varchar(10),
track_nametrack_name char(20),char(20),
descriptiondescription varchar(50),varchar(50),
PRIMARY KEY(track_id),PRIMARY KEY(track_id),
FOREIGN KEY (band_id)FOREIGN KEY (band_id)
REFERENCES BandREFERENCES Band
););
18Rushdi Shams, Dept of CSE, KUET
Important Fact!Important Fact!
 A child table may not have any primary key ofA child table may not have any primary key of
its own. It can make its foreign keys as itsits own. It can make its foreign keys as its
primary keys as well!primary keys as well!
19Rushdi Shams, Dept of CSE, KUET
Entity IntegrityEntity Integrity
 Entity integrity concerns with primary keyEntity integrity concerns with primary key
 It states that “Every table must have a primaryIt states that “Every table must have a primary
key” and “the column(s) that make up thekey” and “the column(s) that make up the
primary key must be unique to identify a rowprimary key must be unique to identify a row
and NOT NULL”and NOT NULL”
20Rushdi Shams, Dept of CSE, KUET
Referential Integrity & PropagationReferential Integrity & Propagation
ConstraintConstraint
 It ensures the integrity of referential relationshipsIt ensures the integrity of referential relationships
between tablesbetween tables
 In a relation between 2 tables, one table has primary keyIn a relation between 2 tables, one table has primary key
and the other a foreign keyand the other a foreign key
 Referential integrity ensures the integrity of the valuesReferential integrity ensures the integrity of the values
of primary and foreign key of parent and child tableof primary and foreign key of parent and child table
 Most database engines call these criteriaMost database engines call these criteria
CONSTRAINTS. Primary and foreign keys are alsoCONSTRAINTS. Primary and foreign keys are also
constraintsconstraints
21Rushdi Shams, Dept of CSE, KUET
Referential Integrity & PropagationReferential Integrity & Propagation
Constraint (continued)Constraint (continued)
 A primary key table is assumed as parent tableA primary key table is assumed as parent table
and a foreign key table is assumed as child tableand a foreign key table is assumed as child table
 If a value in foreign key column in child table isIf a value in foreign key column in child table is
entered, it MUST be present in primary keyentered, it MUST be present in primary key
column in parent tablecolumn in parent table
 Foreign key can have NULL values, but primaryForeign key can have NULL values, but primary
key can NEVER have NULL valueskey can NEVER have NULL values
22Rushdi Shams, Dept of CSE, KUET
Referential Integrity & PropagationReferential Integrity & Propagation
Constraint (continued)Constraint (continued)
 If the primary key value is changed it should beIf the primary key value is changed it should be
CASCADED to force to change foreign key values asCASCADED to force to change foreign key values as
wellwell
 Changing a value in foreign key must check firstly theChanging a value in foreign key must check firstly the
existence of its primary key. If the foreign key isexistence of its primary key. If the foreign key is
changed to NULL, no primary key is required. If it ischanged to NULL, no primary key is required. If it is
changed to NON NULL, the check for primary key ischanged to NON NULL, the check for primary key is
requiredrequired
 If deletion of primary key is required, it is required toIf deletion of primary key is required, it is required to
delete foreign key along with it (CASCADE) or foreigndelete foreign key along with it (CASCADE) or foreign
key firstly then primary keykey firstly then primary key
23Rushdi Shams, Dept of CSE, KUET
Referencial Integrity (continued)Referencial Integrity (continued)
 Creating referential integrity is easy! You haveCreating referential integrity is easy! You have
already done that. Look at the REFERENCESalready done that. Look at the REFERENCES
keyword here. That is ensuring your referentialkeyword here. That is ensuring your referential
integrity.integrity.
 Creating Foreign keysCreating Foreign keys
24Rushdi Shams, Dept of CSE, KUET
Propagation Constraint (continued)Propagation Constraint (continued)
 A propagation constraint is a rule about what to do if a row of a table that isA propagation constraint is a rule about what to do if a row of a table that is
referenced is modified or even deleted.referenced is modified or even deleted.
CREATE TABLE address(CREATE TABLE address(
student_idstudent_id number(10)number(10) NOT NULL,NOT NULL,
student_addressstudent_address varchar(30),varchar(30),
postcodepostcode varchar(10),varchar(10),
PRIMARY KEY (student_id),PRIMARY KEY (student_id),
FOREIGN KEY(student_id) REFERENCES studentFOREIGN KEY(student_id) REFERENCES student
ON DELETE CASCADEON DELETE CASCADE
););
This simply means that if parent table’s student_id is removed, all the childThis simply means that if parent table’s student_id is removed, all the child
table’s student_id s are removed!table’s student_id s are removed!
25Rushdi Shams, Dept of CSE, KUET
Propagation Action/ ReferentialPropagation Action/ Referential
ActionAction
 NO ACTIONNO ACTION:: This corresponds to the restricted
option. It rejects the delete action on the table
containing the primary key reference by the foreign key.
This is the default setting in the absence of a specified
ON DELETE constraint
 CASCADE: This corresponds to the cascades option.
It causes automatic deletion/ modification of associated
rows in the foreign key table following deletion/
modification of the row or rows in the primary key
table
26Rushdi Shams, Dept of CSE, KUET
Propagation Action/ ReferentialPropagation Action/ Referential
Action (continued)Action (continued)
 SET DEFAULT:SET DEFAULT: This causes deletion of the
row in the primary key table followed by setting
the foreign key values to the default specified on
the foreign key
 SET NULL:SET NULL: This corresponds to the nullifies
option. Following deletion of rows in the
primary key table it sets the associated foreign
key values to NULL.
27Rushdi Shams, Dept of CSE, KUET
Super keySuper key
 A super key is a set of columns within a tableA super key is a set of columns within a table
whose values can be used to identify a rowwhose values can be used to identify a row
uniquely.uniquely.
 In real world scenario, it is sometimes difficultIn real world scenario, it is sometimes difficult
to identify primary keys. Then super key is usedto identify primary keys. Then super key is used
to unique identification of rows.to unique identification of rows.
28Rushdi Shams, Dept of CSE, KUET
Super key (continued)Super key (continued)
 In this example, what if the roll is just like 1-60.In this example, what if the roll is just like 1-60.
you have this table for all 4 years’ students! Howyou have this table for all 4 years’ students! How
will you identify them by the roll?will you identify them by the roll?
 So, you can have combinations like {roll, name},So, you can have combinations like {roll, name},
{roll, name, dept}, {roll, name, year, semester},{roll, name, dept}, {roll, name, year, semester},
etc. to uniquely identify them! These areetc. to uniquely identify them! These are
superkeys.superkeys.
RollRoll NameName DeptDept YearYear SemesterSemester
29Rushdi Shams, Dept of CSE, KUET
Candidate keyCandidate key
 It is theIt is the minimal setminimal set of super key.of super key.
 Say, from the previous example, you only canSay, from the previous example, you only can
have super keys as followings (though you mayhave super keys as followings (though you may
have other combinations, but just shorten thathave other combinations, but just shorten that
this time)-this time)-
{roll, name}, {roll, name, dept}, {roll, name,{roll, name}, {roll, name, dept}, {roll, name,
year, semester}year, semester}
In this case, the candidate key is {roll, name}!In this case, the candidate key is {roll, name}!
30Rushdi Shams, Dept of CSE, KUET
Compound keyCompound key
 If you make a key with 2 or more columns, thenIf you make a key with 2 or more columns, then
that is called a compound keythat is called a compound key
 Also calledAlso called Composite keyComposite key oror concatenated keyconcatenated key
 Any one, none, or all, of the multiple attributesAny one, none, or all, of the multiple attributes
within the compound key can be foreign keyswithin the compound key can be foreign keys
31Rushdi Shams, Dept of CSE, KUET
Alternate keyAlternate key
 An alternate key is any of the candidate keys thatAn alternate key is any of the candidate keys that
was not chosen as primary keywas not chosen as primary key
 Say, you have 5 columns A, B, C, D, E and 3Say, you have 5 columns A, B, C, D, E and 3
candidate keys {A, B}, {A, C}, {A, D}, {B, C}candidate keys {A, B}, {A, C}, {A, D}, {B, C}
and {D, E}. You have chosen {A, B} as theand {D, E}. You have chosen {A, B} as the
primary key. So, {A, C}, {A, D}, {B, C} andprimary key. So, {A, C}, {A, D}, {B, C} and
{D, E} will be alternate keys{D, E} will be alternate keys
 Also known asAlso known as Secondary keySecondary key
 Strictly used in data retrieval purposeStrictly used in data retrieval purpose
32Rushdi Shams, Dept of CSE, KUET
Relational Database KeysRelational Database Keys
33Rushdi Shams, Dept of CSE, KUET
ReferencesReferences
 Database Systems:Database Systems:
Design, Implementation, and Management,Design, Implementation, and Management,
Sixth Edition, Rob and CoronelSixth Edition, Rob and Coronel
 www.wikipedia.orgwww.wikipedia.org
 Beginning Database Design by Gavin Powell,Beginning Database Design by Gavin Powell,
Wrox Publications, 2005Wrox Publications, 2005
 Database Systems by Paul Beynon-Devies,Database Systems by Paul Beynon-Devies,
Palgrave Macmillan, 2004Palgrave Macmillan, 2004

Contenu connexe

Tendances

Tendances (20)

MS-SQL SERVER ARCHITECTURE
MS-SQL SERVER ARCHITECTUREMS-SQL SERVER ARCHITECTURE
MS-SQL SERVER ARCHITECTURE
 
Top 100 SQL Interview Questions and Answers
Top 100 SQL Interview Questions and AnswersTop 100 SQL Interview Questions and Answers
Top 100 SQL Interview Questions and Answers
 
MYSQL
MYSQLMYSQL
MYSQL
 
Learning sql from w3schools
Learning sql from w3schoolsLearning sql from w3schools
Learning sql from w3schools
 
SQL
SQLSQL
SQL
 
5. stored procedure and functions
5. stored procedure and functions5. stored procedure and functions
5. stored procedure and functions
 
Sql server T-sql basics ppt-3
Sql server T-sql basics  ppt-3Sql server T-sql basics  ppt-3
Sql server T-sql basics ppt-3
 
MySQL for beginners
MySQL for beginnersMySQL for beginners
MySQL for beginners
 
MYSQL-Database
MYSQL-DatabaseMYSQL-Database
MYSQL-Database
 
Mysql
MysqlMysql
Mysql
 
Introduction to structured query language (sql)
Introduction to structured query language (sql)Introduction to structured query language (sql)
Introduction to structured query language (sql)
 
1. SQL Basics - Introduction
1. SQL Basics - Introduction1. SQL Basics - Introduction
1. SQL Basics - Introduction
 
introdution to SQL and SQL functions
introdution to SQL and SQL functionsintrodution to SQL and SQL functions
introdution to SQL and SQL functions
 
İleri Seviye T-SQL Programlama - Chapter 13
İleri Seviye T-SQL Programlama - Chapter 13İleri Seviye T-SQL Programlama - Chapter 13
İleri Seviye T-SQL Programlama - Chapter 13
 
Using T-SQL
Using T-SQL Using T-SQL
Using T-SQL
 
Sql ppt
Sql pptSql ppt
Sql ppt
 
Database Keys & Relationship
Database Keys & RelationshipDatabase Keys & Relationship
Database Keys & Relationship
 
Ibm db2 10.5 for linux, unix, and windows db2 connect installing and config...
Ibm db2 10.5 for linux, unix, and windows   db2 connect installing and config...Ibm db2 10.5 for linux, unix, and windows   db2 connect installing and config...
Ibm db2 10.5 for linux, unix, and windows db2 connect installing and config...
 
Sql commands
Sql commandsSql commands
Sql commands
 
Introduction to-sql
Introduction to-sqlIntroduction to-sql
Introduction to-sql
 

Similaire à Understanding Database Keys and Integrity

Similaire à Understanding Database Keys and Integrity (20)

Database Tables and Data Types
Database Tables and Data TypesDatabase Tables and Data Types
Database Tables and Data Types
 
Normal forms
Normal formsNormal forms
Normal forms
 
Keys in Database
Keys in DatabaseKeys in Database
Keys in Database
 
Types of keys in dbms
Types of keys in dbmsTypes of keys in dbms
Types of keys in dbms
 
Relational database management system
Relational database management systemRelational database management system
Relational database management system
 
SQL_DBMS_KEYS.pptx
SQL_DBMS_KEYS.pptxSQL_DBMS_KEYS.pptx
SQL_DBMS_KEYS.pptx
 
Intro to Data warehousing lecture 12
Intro to Data warehousing   lecture 12Intro to Data warehousing   lecture 12
Intro to Data warehousing lecture 12
 
Sql ch 12 - creating database
Sql ch 12 - creating databaseSql ch 12 - creating database
Sql ch 12 - creating database
 
Integrity and security
Integrity and securityIntegrity and security
Integrity and security
 
Types of keys dbms
Types of keys dbmsTypes of keys dbms
Types of keys dbms
 
Natural vs.surrogate keys
Natural vs.surrogate keysNatural vs.surrogate keys
Natural vs.surrogate keys
 
Doc 20191022-wa0041
Doc 20191022-wa0041Doc 20191022-wa0041
Doc 20191022-wa0041
 
Joins & constraints
Joins & constraintsJoins & constraints
Joins & constraints
 
Dbms keysppt
Dbms keyspptDbms keysppt
Dbms keysppt
 
Referential integrity
Referential integrityReferential integrity
Referential integrity
 
Data integrity
Data integrityData integrity
Data integrity
 
The Relational Database Model
The Relational Database ModelThe Relational Database Model
The Relational Database Model
 
B & c
B & cB & c
B & c
 
Relational Model
Relational ModelRelational Model
Relational Model
 
The Relational Model
The Relational ModelThe Relational Model
The Relational Model
 

Plus de Rushdi Shams

Research Methodology and Tips on Better Research
Research Methodology and Tips on Better ResearchResearch Methodology and Tips on Better Research
Research Methodology and Tips on Better ResearchRushdi Shams
 
Common evaluation measures in NLP and IR
Common evaluation measures in NLP and IRCommon evaluation measures in NLP and IR
Common evaluation measures in NLP and IRRushdi Shams
 
Machine learning with nlp 101
Machine learning with nlp 101Machine learning with nlp 101
Machine learning with nlp 101Rushdi Shams
 
Semi-supervised classification for natural language processing
Semi-supervised classification for natural language processingSemi-supervised classification for natural language processing
Semi-supervised classification for natural language processingRushdi Shams
 
Natural Language Processing: Parsing
Natural Language Processing: ParsingNatural Language Processing: Parsing
Natural Language Processing: ParsingRushdi Shams
 
Types of machine translation
Types of machine translationTypes of machine translation
Types of machine translationRushdi Shams
 
L1 l2 l3 introduction to machine translation
L1 l2 l3  introduction to machine translationL1 l2 l3  introduction to machine translation
L1 l2 l3 introduction to machine translationRushdi Shams
 
Syntax and semantics
Syntax and semanticsSyntax and semantics
Syntax and semanticsRushdi Shams
 
Propositional logic
Propositional logicPropositional logic
Propositional logicRushdi Shams
 
Probabilistic logic
Probabilistic logicProbabilistic logic
Probabilistic logicRushdi Shams
 
Knowledge structure
Knowledge structureKnowledge structure
Knowledge structureRushdi Shams
 
Knowledge representation
Knowledge representationKnowledge representation
Knowledge representationRushdi Shams
 
L5 understanding hacking
L5  understanding hackingL5  understanding hacking
L5 understanding hackingRushdi Shams
 
L2 Intrusion Detection System (IDS)
L2  Intrusion Detection System (IDS)L2  Intrusion Detection System (IDS)
L2 Intrusion Detection System (IDS)Rushdi Shams
 

Plus de Rushdi Shams (20)

Research Methodology and Tips on Better Research
Research Methodology and Tips on Better ResearchResearch Methodology and Tips on Better Research
Research Methodology and Tips on Better Research
 
Common evaluation measures in NLP and IR
Common evaluation measures in NLP and IRCommon evaluation measures in NLP and IR
Common evaluation measures in NLP and IR
 
Machine learning with nlp 101
Machine learning with nlp 101Machine learning with nlp 101
Machine learning with nlp 101
 
Semi-supervised classification for natural language processing
Semi-supervised classification for natural language processingSemi-supervised classification for natural language processing
Semi-supervised classification for natural language processing
 
Natural Language Processing: Parsing
Natural Language Processing: ParsingNatural Language Processing: Parsing
Natural Language Processing: Parsing
 
Types of machine translation
Types of machine translationTypes of machine translation
Types of machine translation
 
L1 l2 l3 introduction to machine translation
L1 l2 l3  introduction to machine translationL1 l2 l3  introduction to machine translation
L1 l2 l3 introduction to machine translation
 
Syntax and semantics
Syntax and semanticsSyntax and semantics
Syntax and semantics
 
Propositional logic
Propositional logicPropositional logic
Propositional logic
 
Probabilistic logic
Probabilistic logicProbabilistic logic
Probabilistic logic
 
L15 fuzzy logic
L15  fuzzy logicL15  fuzzy logic
L15 fuzzy logic
 
Knowledge structure
Knowledge structureKnowledge structure
Knowledge structure
 
Knowledge representation
Knowledge representationKnowledge representation
Knowledge representation
 
First order logic
First order logicFirst order logic
First order logic
 
Belief function
Belief functionBelief function
Belief function
 
L5 understanding hacking
L5  understanding hackingL5  understanding hacking
L5 understanding hacking
 
L4 vpn
L4  vpnL4  vpn
L4 vpn
 
L3 defense
L3  defenseL3  defense
L3 defense
 
L2 Intrusion Detection System (IDS)
L2  Intrusion Detection System (IDS)L2  Intrusion Detection System (IDS)
L2 Intrusion Detection System (IDS)
 
L1 phishing
L1  phishingL1  phishing
L1 phishing
 

Dernier

What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 

Dernier (20)

What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 

Understanding Database Keys and Integrity

  • 1. Rushdi Shams, Dept of CSE, KUET 1 Database SystemsDatabase Systems Understanding KeysUnderstanding Keys Entity IntegrityEntity Integrity Referential IntegrityReferential Integrity Propagation ConstraintPropagation Constraint Version 1.0Version 1.0
  • 2. 2Rushdi Shams, Dept of CSE, KUET What is keyWhat is key  A key is a CONSTRAINT in field/ column in aA key is a CONSTRAINT in field/ column in a tabletable  Generally, keys are essential in database systemsGenerally, keys are essential in database systems to invoke some integrityto invoke some integrity  By a key, you can tag a field in a table so that theBy a key, you can tag a field in a table so that the field can be used to relate tablesfield can be used to relate tables
  • 3. 3Rushdi Shams, Dept of CSE, KUET Types of keyTypes of key There are 3 types of keys in general. They are-There are 3 types of keys in general. They are-  Primary keyPrimary key  Unique keyUnique key  Foreign keyForeign key
  • 4. 4Rushdi Shams, Dept of CSE, KUET Primary keyPrimary key  Used to uniquely identify a row in a tableUsed to uniquely identify a row in a table  Also calledAlso called Surrogate keySurrogate key  Say, you have a table of names of the students ofSay, you have a table of names of the students of your class and their ages. How can you differyour class and their ages. How can you differ between them? Because many of you have thebetween them? Because many of you have the same name! don’t you? So, what happens if yousame name! don’t you? So, what happens if you try to find out a name “Rezwana” and you findtry to find out a name “Rezwana” and you find there are 5 Rezwanas in the class?there are 5 Rezwanas in the class?  That invokes the idea of primary keyThat invokes the idea of primary key
  • 5. 5Rushdi Shams, Dept of CSE, KUET Primary key (continued)Primary key (continued)  This problem won’t be serious if you had anyThis problem won’t be serious if you had any identifying criteria to differ between 5 Rezwanas.identifying criteria to differ between 5 Rezwanas.  You still can identify 5 Rezwanas by adding anYou still can identify 5 Rezwanas by adding an extra column in that table. Can you say whatextra column in that table. Can you say what field that might be?field that might be?  That is your roll number! So, 5 Rezwanas can beThat is your roll number! So, 5 Rezwanas can be easily identifed by their roll numbers.easily identifed by their roll numbers.  So, roll number is the primary key here.So, roll number is the primary key here.
  • 6. 6Rushdi Shams, Dept of CSE, KUET Primary key (continued)Primary key (continued)
  • 7. 7Rushdi Shams, Dept of CSE, KUET Primary key (continued)Primary key (continued)
  • 8. 8Rushdi Shams, Dept of CSE, KUET Unique KeyUnique Key  Unique keys are applied on the column of aUnique keys are applied on the column of a tabletable  Any field that is UNIQUE key, you will have toAny field that is UNIQUE key, you will have to remember that no 2 entries in that column inremember that no 2 entries in that column in that table will be the samethat table will be the same  So, are you thinking “why there are primary keysSo, are you thinking “why there are primary keys and unique keys? They are same, no?”and unique keys? They are same, no?”
  • 9. 9Rushdi Shams, Dept of CSE, KUET Unique key (continued)Unique key (continued)  No, they are not the same. In real life, when you areNo, they are not the same. In real life, when you are creating tables, you sometimes will not want to let thecreating tables, you sometimes will not want to let the table have the same entry twice (even though that is nottable have the same entry twice (even though that is not the primary key)the primary key)  An example can be, if you have a course table withAn example can be, if you have a course table with primary key COURSE ID and another field COURSEprimary key COURSE ID and another field COURSE NAME- take a look! You will not allow the data entryNAME- take a look! You will not allow the data entry operator to entry the same subject name twice, do you?operator to entry the same subject name twice, do you?  So, making COURSE NAME as UNIQUE will giveSo, making COURSE NAME as UNIQUE will give you that opportunityyou that opportunity
  • 10. 10Rushdi Shams, Dept of CSE, KUET Foreign KeyForeign Key  Foreign keys are copies of primary key in theForeign keys are copies of primary key in the child tablechild table  When two tables are in relation, then child tableWhen two tables are in relation, then child table is that table which depends on the other.is that table which depends on the other.
  • 11. 11Rushdi Shams, Dept of CSE, KUET Foreign key (continued)Foreign key (continued)
  • 12. 12Rushdi Shams, Dept of CSE, KUET Creating Primary keysCreating Primary keys CREATE TABLE student(CREATE TABLE student( student_idstudent_id number(10)number(10) NOT NULLNOT NULL,, student_namestudent_name varchar(20),varchar(20), PRIMARY KEY(student_id)PRIMARY KEY(student_id) ););
  • 13. 13Rushdi Shams, Dept of CSE, KUET Creating Unique keysCreating Unique keys CREATE TABLE course(CREATE TABLE course( course_idcourse_id varchar(10)varchar(10) NOT NULL,NOT NULL, course_namecourse_name varchar(20)varchar(20) UNIQUEUNIQUE,, PRIMARY KEY(course_id)PRIMARY KEY(course_id) ););
  • 14. 14Rushdi Shams, Dept of CSE, KUET Creating Foreign keysCreating Foreign keys CREATE TABLE address(CREATE TABLE address( student_idstudent_idnumber(10)number(10) NOT NULL,NOT NULL, student_addressstudent_address varchar(30),varchar(30), postcodepostcode varchar(10),varchar(10), PRIMARY KEY (student_id),PRIMARY KEY (student_id), FOREIGN KEY(student_id) REFERENCES studentFOREIGN KEY(student_id) REFERENCES student );); BackBack
  • 15. 15Rushdi Shams, Dept of CSE, KUET Case StudyCase Study
  • 16. 16Rushdi Shams, Dept of CSE, KUET Case study (continued)Case study (continued)
  • 17. 17Rushdi Shams, Dept of CSE, KUET Case study (continued)Case study (continued) CREATE TABLE Band(CREATE TABLE Band( band_idband_id varchar(10)varchar(10) NOT NULL,NOT NULL, band_nameband_name char(20),char(20), PRIMARY KEY(band_id)PRIMARY KEY(band_id) );); CREATE TABLE Track(CREATE TABLE Track( track_idtrack_id varchar(10)varchar(10) NOT NULL,NOT NULL, band_idband_id varchar(10),varchar(10), track_nametrack_name char(20),char(20), descriptiondescription varchar(50),varchar(50), PRIMARY KEY(track_id),PRIMARY KEY(track_id), FOREIGN KEY (band_id)FOREIGN KEY (band_id) REFERENCES BandREFERENCES Band ););
  • 18. 18Rushdi Shams, Dept of CSE, KUET Important Fact!Important Fact!  A child table may not have any primary key ofA child table may not have any primary key of its own. It can make its foreign keys as itsits own. It can make its foreign keys as its primary keys as well!primary keys as well!
  • 19. 19Rushdi Shams, Dept of CSE, KUET Entity IntegrityEntity Integrity  Entity integrity concerns with primary keyEntity integrity concerns with primary key  It states that “Every table must have a primaryIt states that “Every table must have a primary key” and “the column(s) that make up thekey” and “the column(s) that make up the primary key must be unique to identify a rowprimary key must be unique to identify a row and NOT NULL”and NOT NULL”
  • 20. 20Rushdi Shams, Dept of CSE, KUET Referential Integrity & PropagationReferential Integrity & Propagation ConstraintConstraint  It ensures the integrity of referential relationshipsIt ensures the integrity of referential relationships between tablesbetween tables  In a relation between 2 tables, one table has primary keyIn a relation between 2 tables, one table has primary key and the other a foreign keyand the other a foreign key  Referential integrity ensures the integrity of the valuesReferential integrity ensures the integrity of the values of primary and foreign key of parent and child tableof primary and foreign key of parent and child table  Most database engines call these criteriaMost database engines call these criteria CONSTRAINTS. Primary and foreign keys are alsoCONSTRAINTS. Primary and foreign keys are also constraintsconstraints
  • 21. 21Rushdi Shams, Dept of CSE, KUET Referential Integrity & PropagationReferential Integrity & Propagation Constraint (continued)Constraint (continued)  A primary key table is assumed as parent tableA primary key table is assumed as parent table and a foreign key table is assumed as child tableand a foreign key table is assumed as child table  If a value in foreign key column in child table isIf a value in foreign key column in child table is entered, it MUST be present in primary keyentered, it MUST be present in primary key column in parent tablecolumn in parent table  Foreign key can have NULL values, but primaryForeign key can have NULL values, but primary key can NEVER have NULL valueskey can NEVER have NULL values
  • 22. 22Rushdi Shams, Dept of CSE, KUET Referential Integrity & PropagationReferential Integrity & Propagation Constraint (continued)Constraint (continued)  If the primary key value is changed it should beIf the primary key value is changed it should be CASCADED to force to change foreign key values asCASCADED to force to change foreign key values as wellwell  Changing a value in foreign key must check firstly theChanging a value in foreign key must check firstly the existence of its primary key. If the foreign key isexistence of its primary key. If the foreign key is changed to NULL, no primary key is required. If it ischanged to NULL, no primary key is required. If it is changed to NON NULL, the check for primary key ischanged to NON NULL, the check for primary key is requiredrequired  If deletion of primary key is required, it is required toIf deletion of primary key is required, it is required to delete foreign key along with it (CASCADE) or foreigndelete foreign key along with it (CASCADE) or foreign key firstly then primary keykey firstly then primary key
  • 23. 23Rushdi Shams, Dept of CSE, KUET Referencial Integrity (continued)Referencial Integrity (continued)  Creating referential integrity is easy! You haveCreating referential integrity is easy! You have already done that. Look at the REFERENCESalready done that. Look at the REFERENCES keyword here. That is ensuring your referentialkeyword here. That is ensuring your referential integrity.integrity.  Creating Foreign keysCreating Foreign keys
  • 24. 24Rushdi Shams, Dept of CSE, KUET Propagation Constraint (continued)Propagation Constraint (continued)  A propagation constraint is a rule about what to do if a row of a table that isA propagation constraint is a rule about what to do if a row of a table that is referenced is modified or even deleted.referenced is modified or even deleted. CREATE TABLE address(CREATE TABLE address( student_idstudent_id number(10)number(10) NOT NULL,NOT NULL, student_addressstudent_address varchar(30),varchar(30), postcodepostcode varchar(10),varchar(10), PRIMARY KEY (student_id),PRIMARY KEY (student_id), FOREIGN KEY(student_id) REFERENCES studentFOREIGN KEY(student_id) REFERENCES student ON DELETE CASCADEON DELETE CASCADE );); This simply means that if parent table’s student_id is removed, all the childThis simply means that if parent table’s student_id is removed, all the child table’s student_id s are removed!table’s student_id s are removed!
  • 25. 25Rushdi Shams, Dept of CSE, KUET Propagation Action/ ReferentialPropagation Action/ Referential ActionAction  NO ACTIONNO ACTION:: This corresponds to the restricted option. It rejects the delete action on the table containing the primary key reference by the foreign key. This is the default setting in the absence of a specified ON DELETE constraint  CASCADE: This corresponds to the cascades option. It causes automatic deletion/ modification of associated rows in the foreign key table following deletion/ modification of the row or rows in the primary key table
  • 26. 26Rushdi Shams, Dept of CSE, KUET Propagation Action/ ReferentialPropagation Action/ Referential Action (continued)Action (continued)  SET DEFAULT:SET DEFAULT: This causes deletion of the row in the primary key table followed by setting the foreign key values to the default specified on the foreign key  SET NULL:SET NULL: This corresponds to the nullifies option. Following deletion of rows in the primary key table it sets the associated foreign key values to NULL.
  • 27. 27Rushdi Shams, Dept of CSE, KUET Super keySuper key  A super key is a set of columns within a tableA super key is a set of columns within a table whose values can be used to identify a rowwhose values can be used to identify a row uniquely.uniquely.  In real world scenario, it is sometimes difficultIn real world scenario, it is sometimes difficult to identify primary keys. Then super key is usedto identify primary keys. Then super key is used to unique identification of rows.to unique identification of rows.
  • 28. 28Rushdi Shams, Dept of CSE, KUET Super key (continued)Super key (continued)  In this example, what if the roll is just like 1-60.In this example, what if the roll is just like 1-60. you have this table for all 4 years’ students! Howyou have this table for all 4 years’ students! How will you identify them by the roll?will you identify them by the roll?  So, you can have combinations like {roll, name},So, you can have combinations like {roll, name}, {roll, name, dept}, {roll, name, year, semester},{roll, name, dept}, {roll, name, year, semester}, etc. to uniquely identify them! These areetc. to uniquely identify them! These are superkeys.superkeys. RollRoll NameName DeptDept YearYear SemesterSemester
  • 29. 29Rushdi Shams, Dept of CSE, KUET Candidate keyCandidate key  It is theIt is the minimal setminimal set of super key.of super key.  Say, from the previous example, you only canSay, from the previous example, you only can have super keys as followings (though you mayhave super keys as followings (though you may have other combinations, but just shorten thathave other combinations, but just shorten that this time)-this time)- {roll, name}, {roll, name, dept}, {roll, name,{roll, name}, {roll, name, dept}, {roll, name, year, semester}year, semester} In this case, the candidate key is {roll, name}!In this case, the candidate key is {roll, name}!
  • 30. 30Rushdi Shams, Dept of CSE, KUET Compound keyCompound key  If you make a key with 2 or more columns, thenIf you make a key with 2 or more columns, then that is called a compound keythat is called a compound key  Also calledAlso called Composite keyComposite key oror concatenated keyconcatenated key  Any one, none, or all, of the multiple attributesAny one, none, or all, of the multiple attributes within the compound key can be foreign keyswithin the compound key can be foreign keys
  • 31. 31Rushdi Shams, Dept of CSE, KUET Alternate keyAlternate key  An alternate key is any of the candidate keys thatAn alternate key is any of the candidate keys that was not chosen as primary keywas not chosen as primary key  Say, you have 5 columns A, B, C, D, E and 3Say, you have 5 columns A, B, C, D, E and 3 candidate keys {A, B}, {A, C}, {A, D}, {B, C}candidate keys {A, B}, {A, C}, {A, D}, {B, C} and {D, E}. You have chosen {A, B} as theand {D, E}. You have chosen {A, B} as the primary key. So, {A, C}, {A, D}, {B, C} andprimary key. So, {A, C}, {A, D}, {B, C} and {D, E} will be alternate keys{D, E} will be alternate keys  Also known asAlso known as Secondary keySecondary key  Strictly used in data retrieval purposeStrictly used in data retrieval purpose
  • 32. 32Rushdi Shams, Dept of CSE, KUET Relational Database KeysRelational Database Keys
  • 33. 33Rushdi Shams, Dept of CSE, KUET ReferencesReferences  Database Systems:Database Systems: Design, Implementation, and Management,Design, Implementation, and Management, Sixth Edition, Rob and CoronelSixth Edition, Rob and Coronel  www.wikipedia.orgwww.wikipedia.org  Beginning Database Design by Gavin Powell,Beginning Database Design by Gavin Powell, Wrox Publications, 2005Wrox Publications, 2005  Database Systems by Paul Beynon-Devies,Database Systems by Paul Beynon-Devies, Palgrave Macmillan, 2004Palgrave Macmillan, 2004