Database normalization
COPYRIGHT DISCLAIMER: Presentation aggregates information from multiple open-access resources. Author does not claim for copyright.
2. Нормалізація / Normalization
Якщо база даних ненормалізована, вона може
містити аномалії, які є нічним кошмаром для
кожного адміністратора баз даних. Управління
базою даних, що містить аномалії, майже
неможливо.
If a database design is not perfect, it may contain
anomalies, which are like a bad dream for any
database administrator. Managing a database
with anomalies is next to impossible.
117
3. Аномалії оновлення / Modification
anomalies
Якщо дані розкидані і не пов'язані між собою належним чином, це
може призвести до дивних ситуацій. Наприклад, коли ми
намагаємося оновити один елемент даних, який має копії,
розкидані по декількох місцях, декілька екземплярів
оновлюються правильно, тоді як декілька інших залишаються зі
старими значеннями. Такі випадки залишають базу даних у
неузгодженому стані.
If data items are scattered and are not linked to each other properly,
then it could lead to strange situations. For example, when we try
to update one data item having its copies scattered over several
places, a few instances get updated properly while a few others are
left with old values. Such instances leave the database in an
inconsistent state.
118
4. Student ID Student Name Student Phone Assigned Subject
1 A 1234 Programming
2 A 1234 Databases
3 B 2345 Biology
4 C 3456 Math
5 D 4567 Physics
119
Якщо телефон студента A зміниться, його необхідно оновити
у всіх відповідних записах таблиці.
If student’s A phone changes, must change it in each table record
assigned to this student.
5. Аномалії видалення / Deletion
anomalies
• В результаті спроби видалити запис, деякі
його частини не були видалені через
незнання того, що дані також зберігаються
десь в іншому місці.
• We tried to delete a record, but parts of it was
left undeleted because of unawareness, the
data is also saved somewhere else.
120
6. Student ID Student Name Student Phone Assigned Subject
1 A 1234 Programming
2 A 1234 Databases
3 B 2345 Biology
4 C 3456 Math
5 D 4567 Physics
121
Якщо видалити записи про біологію з бази даних, будуть також
втрачені усі дані про студента B.
If we delete Biology entries from the database, we also loose all
data about student B.
7. Аномалії вставки / Insert anomalies
Спроба вставити дані в запис, який взагалі не
існує.
We tried to insert data in a record that does not
exist at all.
122
8. Student ID Student Name Student Phone Assigned Subject
1 A 1234 Programming
2 A 1234 Databases
3 B 2345 Biology
4 C 3456 Math
5 D 4567 Physics
123
В базі даних неможливо зберегти дані про новий предмет,
тому що він не буде пов’язаний з жодним студентом.
It is impossible to store data about the new subject, since it
won‘t be associated to any student.
English
9. Перша нормальна форма / First
normal form
Це правило визначає, що всі атрибути у
відношенні повинні мати атомарні домени.
Значення в атомарному домені є
неподільними одиницями. Кожен атрибут
повинен містити лише одне значення з його
попередньо визначеного домену.
This rule defines that all the attributes in a relation
must have atomic domains. The values in an
atomic domain are indivisible units. Each
attribute must contain only a single value from its
pre-defined domain.
124
11. Друга нормальна форма / Second
normal form
• Для дотримання другої нормальної форми, кожен
не первинний атрибут повинен повністю
функціонально залежати від первинного ключа.
Тобто, якщо X → A справедливо, то не повинно бути
жодної підмножини Y множини X, для якої Y → A
також справедливо.
• If we follow second normal form, then every non-prime
attribute should be fully functionally dependent on
prime key attribute. That is, if X → A holds, then there
should not be any proper subset Y of X, for which Y →
A also holds true.
126
12. Функціональна залежність /
Functional Dependency
Функціональна залежність (FD) – це сукупність
обмежень між двома атрибутами у відношенні.
Функціональна залежність говорить, що якщо два
кортежі мають однакові значення для атрибутів A1,
A2, ..., An, то ці два кортежі повинні мати однакові
значення для атрибутів B1, B2, ..., Bn.
Functional dependency (FD) is a set of constraints
between two attributes in a relation. Functional
dependency says that if two tuples have same values
for attributes A1, A2,..., An, then those two tuples must
have to have same values for attributes B1, B2, ..., Bn.
127
13. Функціональна залежність представлена знаком
стрілки (→), тобто X → Y, де X функціонально
визначає Y. Атрибути лівої частини визначають
значення атрибутів у правій частині.
Functional dependency is represented by an arrow
sign (→) that is, X→Y, where X functionally
determines Y. The left-hand side attributes
determine the values of attributes on the right-
hand side.
• Рефлексивність. Якщо A – це набір атрибутів і
B є підмножиною A, то A містить B.
• Reflexive rule. If A is a set of attributes and B is
subset of A, then A holds B.
128
14. • Доповнення. Якщо A → B виконується, та Y є
множиною атрибутів, то AY → BY також виконується.
Це додавання атрибутів до залежностей, не змінює
основних залежностей.
• Augmentation rule. If A → B holds and Y is attribute
set, then AY → BY also holds. That is adding attributes
in dependencies, does not change the basic
dependencies.
• Транзитивність. Те ж, що і транзитивне правило в
алгебрі, якщо виконується A → B, і B → C, то A → C
також має місце. A → B функціонально визначає B.
• Transitivity rule. Same as transitive rule in algebra, if A
→ B holds and B → C holds, then A → C also holds. A →
B is called as a functionally that determines b.
129
15. 130
Часткова залежність
Partial dependency
A = {Stu_Name, Proj_Name}
X = {Stu_ID, Proj_ID}
Stu_ID -> Stu_Name
Proj_ID -> Proj_Name
A1 = {Stu_Name, Proj_ID}
X1 = {Stu_ID}
X1 -> A1
A2 = {Proj_Name}
X2 = {Proj_ID}
X2 -> A2
16. Третя нормальна форма / Third
normal form
Відношення, яке має бути у третій нормальній формі, має бути у другій
нормальній формі, а також має виконуватися:
• немає нетривіальних атрибутів, які транзитивно залежать від
первинного ключа;
• для будь-якої нетривіальної функціональної залежності X → A, X має
бути супер-ключем або A має бути первинним ключем.
For a relation to be in Third Normal Form, it must be in Second Normal form
and the following must satisfy:
• No non-prime attribute is transitively dependent on prime key attribute.
• For any non-trivial functional dependency, X → A, then either X is a super
key or, A is prime attribute.
131
17. Тривіальна функціональна залежність /
Trivial Functional Dependency
• Якщо виконується функціональна залежність X → Y, де Y – підмножина
X, то вона називається тривіальною.
• If a functional dependency X → Y holds, where Y is a subset of X, then it is
called a trivial.
• Якщо виконується X → Y, де Y не є підмножиною X, то функціональну
залежність називають нетривіальною.
• If an functional dependency X → Y holds, where Y is not a subset of X,
then it is called a non-trivial.
• Якщо виконується X → Y, де перетин X та Y = Φ, то функціональна
залежність вважається абсолютно нетривіальною.
• If an functional dependency X → Y holds, where x intersect Y = Φ, it is said
to be a completely non-trivial.
132
19. Нормальна форма Бойса-Кодда /
Boyce-Codd Normal Form
Нормальна форма Бойса-Кодда (BCNF) є
продовженням третьої нормальної форми на
більш строгих умовах. BCNF стверджує, що для
будь-якої нетривіальної функціональної
залежності, X → A, X має бути супер-ключем.
Boyce-Codd Normal Form (BCNF) is an extension of
Third Normal Form on strict terms. BCNF states
that for any non-trivial functional dependency, X
→ A, X must be a super-key.
134
20. Декомпозиція схеми відношення /
Relation scheme decomposition
Декомпозицією схеми відношення R = {A1, A2, …,
An} називається заміна її сукупністю підмножин
R, таких що їх об’єднання дає R. При цьому
допускається, що підмножини можуть
перетинатися.
Relation R = {A1, A2, …, An} scheme decomposition is
a procedure of replacement of R with the set of
sub-relations which union gives R. Moreover, the
intersection of such sub-sets is allowed.
136
21. Input: R0 = {Name, Address, Product, Amount, Price,
Date}
Address is non-atomic attribute => R is not in 1NF
SOLUTION: Address => {City, Region}
Output: R1NF = {Name, City, Region, Product, Amount,
Price, Date}
137
Address
Lozova, Kharkiv Oblast
Sumy, Sumska Oblast
PROBLEM
22. Input: R1NF = {Name, City, Region, Product, Amount, Price,
Date}
Name -> {City, Region}
Name -> {Amount, Price, Date}
Product -> {Amount, Price, Date}
PROBLEM: R1NF has partial dependencies => R1NF is not in
2NF
SOLUTION: Split R1NF into several relations
Output: R2NF = RFactory AND RProduct AND RPF
RFactory = {Factory_ID, Name, City, Region}
RProduct = {Product_ID, Product}
RManufactured = {Factory_ID, Product_ID,
Amount, Price, Date}
138
24. Input: R2NF = RFactory AND RProduct AND RManufactured
Product_ID -> Product
{Factory_ID, Product_ID} -> {Amount, Price, Date}
Factory_ID -> {Name, City, Region}, City -> Region
PROBLEM: R2NF has transitive dependency Factory_ID -
> City -> Region => R2NF is not in 3NF
SOLUTION: Split RFactory into several relations
Output: R3NF = R2NF AND RCity AND RRegion
RFactory = {Factory_ID, City_ID}
RCity = {City_ID, City, Region_ID}
RRegion = {Region_ID, Region}
140
26. Четверта нормальна форма / Fourth
normal form
Відношення знаходиться в четвертій нормальній
формі, якщо воно знаходиться у нормальній
формі Бойса-Кодда та не містить
нетривіальних багатозначних залежностей.
A relation is in the fourth normal form if it is already
in the Boyce-Codd normal form and does not
contain any non-trivial multivalued
dependencies.
142
27. П’ята нормальна форма / Fifth
normal form
Відношення знаходиться у п’ятій нормальній
формі тоді та тільки тоді, коли кожна
нетривіальна залежність з’єднання у ній
визначається потенційним ключем
(ключами) цього відношення.
A relation is in the fifth normal form if and only
if every non-trivial join dependency in that
relation is implied by the candidate keys.
143
28. Доменно-ключова нормальна
форма / Domain-key normal form
Відношення знаходиться у доменно-ключовій
нормальній формі тоді та тільки тоді, коли
кожне накладене на неї обмеження є логічним
наслідком обмежень доменів і обмежень
ключів, накладених на дане відношення.
A relation is in the domain-key normal form if and
only if it contains no constraints other than
domain constraints and key constraints.
144
29. Шоста нормальна форма / Sixth
normal form
Відношення знаходиться у шостій нормальній
формі тоді і тільки тоді, коли вона задовольняє
усім нетривіальним залежностям з’єднання
(тобто, не може бути піддана подальшій
декомпозиції без втрат).
A relation is in the sixth normal form if and only if it
satisfies all non-trivial join dependencies (that is
it cannot be further decomposed without loss).
145
30. Предметна область для контролю: ІТ
компанія / Subject area for tests: IT company
146