데이터베이스 정규화란?

데이터베이스 정규화는 데이터베이스 설계에서 중복 데이터를 줄이는 것으로, 이를 통해 데이터 무결성을 유지하고 DB저장 용량을 줄일 수 있다. 이를 통해 테이블 구조를 효율적으로 만들고 데이터 삽입 ,삭제,수정 시 발생할 수 있는 이상 현상을 방지한다.

삽입 이상(Insertion Anomaly): 새 데이터를 삽입할 때, 의도치 않은 데이터가 삽입됨으로써 생기는 데이터 불일치
삭제 이상(Deletion Anomaly): 데이터를 삭제할 때 의도치 않은 데이터까지 삭제됨으로써 생기는 데이터의 불일치
갱신이상(Modification Anomaly): 중복된 데이터 중 일부를 갱신할 때 의도치 않은 데이터가 갱신됨으로써 생기는 데이터의 불일치

1. 제 1 정규형(원자성)

모든 열이 원자값(하나의 값)을 가져야 한다. 중첩된 테이블이나 복수의 값을 허용하는 칼럼을 제거한다.

제 1 정규화 예시


2. 제 2 정규형(부분 함수 종속성 제거)

기본 키가 아닌 속성이 기본 키의 부분집합에 종속되지 않도록 한다. 다음 테이블의 기본키는 학생 번호와 수강과목으로 구성되어 있는데, 성적은 두가지 값을 모두 사용해서 값이 정해지지만, 강의실은 강좌이름으로 결정이 되기 때문에 부분 함수 종속성에 해당한다. 따라서 강의실과 강좌이름을 다른 테이블로 분리해야한다. 즉, 기본 키의 일부에만 의존하는 칼럼을 제거하여 부분 함수 종속성을 없앤다.

제 2 정규화 예시

3. 제 3 정규형(이행적 종속성 제거)

기본키가 아닌 모든 속성이 기본키에만 종속되도록 한다. 기본 키 이외의 다른 속성에 의존하는 칼럼을 제거한다. 이행적 종속이란 A->B, B->C일 때, A->C 인 경우를 의미한다. 한 테이블에서 저런 구조를 가지고 있는 경우를 제거하는 것이 제 3 정규의 목표이다.

제 3 정규화 예시

4. BCNF(Boyce-Code Normal Form)

모든 결정자가 후보키여야 한다. 즉, 후보키가 아닌 속성은 다른 어떤 속성에도 종속되지 않아야 한다.

후보키란 최소성과 유일성을 만족하는 속성의 집합을 의미한다. 

 

5. 제 4 정규형(다치 종속성 제거)

하나의 테이블에서 여러 독립적인 다치 종속성을 분리한다.

6. 제 5 정규형(조인 종속성 제거)

테이블을 분해하더라도 데이터를 잃지 않고 다시 조인할 수 있어야 한다.

정규화의 장점

1) 중복 데이터 최소화

2) 데이터 무결성 유지

3) 효율적인 쿼리 구조

정규화의 단점

복잡성 증가. 

반정규화

데이터베이스 성능 향상을 위해 데이터의 중복을 허용하는 정규화의 반대 의미. 정규화를 통해 종속성과 활용성은 향상되었지만, Join을 많이하고 다량의 범위를 자주 처리해야하는 경우 수행속도가 느려져 반정규화를 수행하기도 한다.
계산 칼럼 추가, 테이블 수직 분할, 테이블 수평 분할, 테이블 병합 등으로 반정규화를 실행할 수 있다.

Part 3. The Relational Data Model and SQL

Book_Chapter 6 Basic SQL

  1. SQL Data Definition and Data Types
  2. Specifying Constraints in SQL
  3. Basic Retrieval Queries in SQL
  4. INSERT, DELETE, and UPDATE Statements in SQL
  5. Additional Features of SQL
  6. Summary

1. SQL Data Definition and Data Types

  • SQL(Structured Query Language) : Data Definition in SQL
    relation->table / tuple-> row / attribute->column
  • Schema and Catalog concepts
    - SQL Schema: 스키마 이름으로 식별되고, 스키마 authorization identifier와 각 요소에 대한 descriptor를 갖는다.
    - Create Schema <SCHEMA name> Authorization <USER NAME>
  • Catalog : named collection of schema
    - 카탈로그는 카탈로그에 있는 모든 스키마에 대한 정보와, 스키마의 descripter를 제공하는 information_schema를 포함한다.
    - 카탈로그들이 생성되면 자료사전에 저장되기 때문에 자료 사전이라고 부르기도 함.
    - 카탈로그에 저장된 정보를 meta data라고 한다.
  •  Create table
    - create table <table이름>.<schema이름> ( <column name>, <data type>,<constraints> )
    - Data type
    (1) numeric: integer, real, formatted numberedecimal(소수점 전 digit 수, 소수점 이후 digit 수) 
    (2) character(String data type): char(n) - 고정길이, varchar(n) - 가변길이
    (3) bit-string data type: bit(n)-고정, bit varying(n)- 가정
    (4) date data type: YYYY-MM-DD(유효값만 인정)
    (5) time data type: HH:MM:SS
    (6) timestamp data type: date + time+ time qualifier
    (7) interval data type: time interval
  • DROP
    - DROP SCHEMA <schema name> CASCADE: 스키마와 관련된 모든 테이블, 도메인, 요소들을 삭제
    - DROP SCHEMA <schema name> RESTRICT: 스키마의 element가 없는 경우 스키마를 삭제
    - DROP TABLE <relatioion name> CASCADE: 릴레이션과 해당 릴레이션을 참조하는 릴레이션을 삭제
    - DROP TABLE <relatioion name> RESTRICT: 릴레이션이 다른 constraints(foreign key/ view)에 참조되지 않을 경우 삭제
  • ALTER
    - add an attribute: ALTER TABLE <table>.<schema> ADD <attribute>;
    - drop an attribute(cascade, restricted) : ALTER TABLE <table>.<schema> DROP <attribute> CASCADE;
    - drop and add default value: ALTER TABLE <table>.<schema> ALTER <attribute> DROP DEFAULT;
                                           ALTER TABLE <table>.<schema> ALTER <attribute> SET DEFAULT "value";
    - drop named constraint: ALTER TABLE <table>.<schema> DROP CONSTRAINTS <attribute> CASCADE;

2. Specifying Constraints in SQL

  • SQL(Structured Query Language) : Data Definition in SQL
    - Referential Integrity in SQL
    (1) No Action: update나 delete를 거절
    (2) Casacade: 참조하는 모든 튜플을 삭제
    (3) Set Null/Set Default: 참조 튜플의 값을 null이나 default로 설정
    - Primary Key/Foreign Key + References <Table>
  • Constraints
    (1) 속성 데이터형 정의: create domain ssn_Type as char(9);
    (2) not null constraint: key constraint or null is not allowed.
    (3) 기본 값 정의: default < value>
    (4) base table &  virtual table
    - base table은 create table로 선언된 relation을 의미. virtual table은 create view로 선언된 relation

3. Queries SQL

  • Basics : SELECT<attribute list> FROM <table list> WHERE <condition>;
    <attribute list> : 질의 결과로 나타나는 속성 이름들
    <table list> : operand tables
    <condition> : search condition(Boolean search expressions)
  • Aliasing : 서로 다른 테이블의 속성 이름이 같은 경우
    (1) qualified name을 사용
    (2) join할 때, table name을 새롭게 설정
  • Table as Set
    - DISTINCT : relation=서로 다른 레코드의 집합 vs table=list(duplicated tuples)
    - Set operation(union compatible, no duplicate): UNION, INTERSECT, EXCEPT...
  • Like
    - % : 연속된 임의의 character. 부분 string match
    -  _ :  single character
  • Order by <attribute>desc/asc
  • Nested Queries: 쿼리 안에 쿼리가 존재하는 경우.
    - IN이나 =가 사용되었을 경우 nested Queries는 단일 select 문으로 표현될 수 있다.
    - name confliction on unqualified name: qualified name을 사용할 때, inner query에서 어떤 query의 속성을 사용하는지 확인이 용이함
  •  IN operator: compare a value v(튜플) with a set of value V(집합) ->boolean값을 반환
  • ALL(v >ALL V): tuple v가 집합 V의 모든 값보다 클 경우 true
  • EXIST: correlate된 nested query가 비어있으면 true, 아니면 false를 리턴
  • UNIQUE: 쿼리의 결과에 중복하는 튜플이 존재하지 않을때(DISTINCT)
  • CONTAINS(=divide-by): sql92의 표준에 포함이 되어 있지 않음. FOR ALL-> EXCEPTION, NOT EMPTY 확인
  • built-in function(count, sum, max, min, avg...): Select문이나 having절에서 사용 가능
  • Having clause & group by
    - group by: 그룹별로 집계하는 조건
    - having: group에 대한 선택 조건. group by가 항상 필요함.

4. INSERT, DELETE, and UPDATE Statements in SQL

  • INSERT INTO <table name> values (tuple value), (tuple value)....
  • DELETE FROM <table name> WHERE <condition>
    - where 조건이 없으면 table의 모든 tuple을 삭제한다.
  • UPDATE <table name> SET <attribute name> = <new value>,... WHERE <condition>

참고문헌 : Fundamentals of Database Systems 7th Edition

Part 3. The Relational Data Model and SQL

Book_Chapter 5 The Relational Data Model and Relational Database Constraints

  1. Relational Model Concepts
  2. Relational Model Constraints and Relational Database Schemas
  3. Update Operations, Transactions, and Dealing with Constraint Violations
  4. Summary

1. Relational Model Concepts

  • 용어정리
    용어 정의
    Domain atomic(formal relational model에서 indivisible한 ) 값의 집합
    ex) name, data type, format, additional information
    Tuples relation에 들어가는 실제 데이터 값
    (<attribute>,<value>)의 set
    Attributes relation의 속성 값
    Relations relation schema의 실제 데이터 instance
    n-tuple의 집합
    (dynamic)
    Relation Schema relation의 구조(메타데이터)
    almost static
    cardinality tuple의 수
    degree relation의 속성의 개수
  • Relation Schema R
    - R: relation의 이름
    - A1, A2, ...., An : attribute의 이름
    - domain of Ai = dom(Ai)
    - domain은 같아도 다른 attribute로 설정할 수 있다.
  • Relation instance r(R)
    - relation schema R의 실제 데이터 relation
    - r = {t1, t2, ...., tm}
      ti = 정렬된 list <v1, v2, ...vn>
      vi →{dom(Ai) null}, 1<= i <= n
    - relation r(R)은 relation schema R을 정의하는 모든 domain의 cartesian product의 부분집합이다.
     cartesian product는 domain의 모든 가능한 값의 조합을 의미한다.
     r(R) ⊆ (dom(A1) × dom(A2) × . . . × (dom(An))
  • Ordering of tuples in a Relation
    - relation은 tuple의 집합이기 때문에 ordering이 없지만, record에는 순서가 있다.
    - relation을 table로 표현하기 때문에 열에도 특정 순서가 존재한다.
  • values in tuples
    - tuple의 값으로 복합/다중 속성은 사용 못한다.[제 1정규형]
    - value값이 not available/ not apply / unknown의 경우 null을 사용한다.
  • Interpretation (Meaning) of a Relation
    - Relational data model에서는 entity type, relationship type, attribute를 Relation으로 일관되게 표현한다..
    - Relation schema : 선언
    - fact about entities : relation instance
    - relationship among entities : relation instance
  • Relation Model Notation
    - relation schema R of degree n : R(a1, a2, .... an)
    - n-tuple t in relation r(R)
     (1) t = <v1, v2, ...vn>
     (2) value vi in t for attribute Ai : t[Ai]
     (3) subtuple of vlue<vu, vw, ... vz> from tuple t: t[Au, Aw, ... Az]
     (4) qualified attribute name : relationName.AttributeName(서로 다른 schema에서 사용 가능)

2. Relational Model Constraints and Relatio1nal Database Schemas

  • Domain constraints
    - 각 튜플 내에서 각 특성 A의 값이 도메인 dom(A)의 atomic value(단순, 단일 속성)이어야 한다.
    - integer(short, long), real(single, double), character, fixed-length string, variable-length string, date, time, money data type....
  • Key constraints
    - relation은 tuples의 set이기 때문에 모든 tupels는 distinct해야한다. key의 값은 relation의 한 tuple을 찾는데 사용된다. 
    - super key : 한 relation내에 있는 속성들의 집합으로 구성된 키로, relation을 유일하게 지칭할 수 있는 attribute의 subset을 의미한다.(학번 + 생년월일...)
    - 모든 relation schema는 적어도 한 개 이상의 super key를 가져야 한다.
    - Key K of relation schema R(minimal super key) : superkey이면서 K에서 속성들을 제거 했을때, super key가 되기 위한 최소의 조건의 key를 minimal key라고 한다.
    - key는 mini-world에 의해 결정되며 relation schema(meta-data)에서 정의된다:
    time-invariant
    - relation schema에는 한 개 이상의 key가 존재한다. (candidate key)

    - candidate key 중 단순속성 or 적은 수의 속성을 갖는 복합속성을 선택하여 primary key를 정의한다.
  •  
  • Relational Database Schema
    - Relational database는 여러개의 relation으로 구성된다.

    - relational database schema S는 Ralation schemas의 집합이면서, integrity  constraints의 집합이다.
    - Relational database instance DB : integrity constraint를 만족하는 relation instance의 집합이다.
  • Entity & Referential Integrity
    (1) entity integrity constraint(개체 무결성 제약조건) : primary key는 null이 되면 안된다.
    (2) referential integrity constraint(참조 무결성 제약조건) : 한 relation의 tuple에서 다른 relation을 참조할 때는 항상 참조되는 tuple이 존재해야한다.
     - 참조 무결성 제약 조건은 두 relation사이에 지정되며 두 relation에서 tuple 간의 일관성을 유지하기 위해 사용된다. 
  • Foreign key
    - Relation R1이 참조하는 Relation R2의 기본키와 같은 R1 릴레이션의 속성을 Foreign key로 정의한다.

    - dom(FK) = dom(PK)
  • Semantic integrity constraint : mini world의 일반적 제약조건으로 대부분의 DBMS에서 지원하지 않는다. (ex. 최대 노동시간은 일주일에 52시간을 초과하지 않는다.)

3. Update Operations, Transactions, and Dealing with Constraint Violations

  • Insert Operation : 새로운 tuple을 relation에 추가하는 것
    - domain constraint : 추가하려는 tuple의 속성 값이 domain에 존재하지 않는 경우
    - key constraint : 추가되는tuple의 key값이 relation의 다른 tuple에 이미 있는 경우
    - entity constraint : 새 tuple의 Primary key의 값이 null인 경우
    - referential constraint : Foreign key의 값이 참조하는 튜플이 존재하지 않는 경우
  • Delete Operation : 기존 relation에서 tuple을 삭제하는 것
    - referential constraint : 삭제하려는 tuple이 다른 relation에 의해 참조되는 경우
    (1) delete를 거절
    (2) 삭제된 tuple을 참조하는 모든 tuple을 삭제
    (3) 참조하는 값을 null 또는 다른 값으로 대치(참조하는 속성이 key이면 null로 대치 할 수 없음)
  • Modify Operation
    - delete + insert
  • Defining Relation : 설계된 db를 dbms에서 정의하는 법
    - Relational DBMS 정의: DDL(Data Definition Language) =>SQL
    - Relational database schema 정의
    - Domain 정의
    - Relation정의 : Relation name, Attribute name & Domains, Primary key and other keys, foreign key

 

 

 


4. Summary

 

참고문헌 : Fundamentals of Database Systems 7th Edition

Part 2. Conceptual Data Modeling and Database Design

Book_Chapter 4 The Enhanced Entity-Relationship(EER) Model

  1. Subclasses, Superclasses, and Inheritance
  2. Specialization and Generalization
  3. Constraints and Characteristics of Specialization and Generalization Hierarchies
  4. Modeling of UNION Types Using Categories
  5. A Sample UNIVERSITY EER Schema, Design Choices, and Formal Definitions
  6. Example of Other Notation :Representing Specializaiton and Generalization in UML Class Diagrams
  7. Data Abstaraction, Knowledge Representation, and Ontology Concepts
  8. Summary

1. Subclasses, Superclasses, and Inheritance

2. Specialization and Generalization

  •  용어 정의 
    용어 정의
    Entity type(=class) 같은 속성을 가진 개체의 집합
    class 개체의 집합
    Subclass super class에 포함되는 entity의 부분 집합 super class와 subclass를
    IS-A relation ship으로 표현
    Superclass subclass의 본체
    Inheritance superclass의 속성을 subclass가 갖게 되는 것을 의미
    Specialization entity type(super class)의 subclass를 정의하는 프로세스.
    super class를 specialization하면 superclass의 속성을 subclass가 상속받는다.
    Generalization 여러 entity type에서 공통 기능을 식별하여 단일 superclass로 만드는 프로세스.
    subclass를 generalization하면 superclass가 된다.
  • IS-A Hierarchies를 사용하는 이유 
    - subclss에 특정한 descriptive 속성을 추가하기 위해서
    - relationship에 참여하는 entity를 식별하기 위해서
  • Subclassses in data modeling
    - model specific attributes : subclass는 superclass의 특성을 상속받고, 추가적인 속성을 갖는다. 
    - model specific relationship on subclass

3. Constraints and Characteristics of Specialization and Generalization Hierarchies

  • predicate-defined/attribute-defined
    - subclass S의 membership이 같은 조건으로 정의되는 속성을 supclass C의 추가 속성으로 만들었을 때, Subclass S의 defining predicate으로 표현한다. S=C[P]
    - 모든 specialize된 subclass가 superclass의 공통 속성으로 membership condition을 가질 때, specialization은 그 자체로 attributed-defined specialization으로 정의되고, 그 속성은 defining attribute라고 부른다.
  • user-defined
    -subclass에서 membership을 결정하는 조건이 없을 경우 subclass는 사용자가 subclass에 entity를 추가하는 작업을 수행하고, user-defined subclass가 된다. membership은 자동으로 결정되는 것이 아니라 entity에 따라 별개로 specify된다.
    - diagram에서는 circle이 없는 형태로 그려진다.
  • disjoint / overlapping / total / partial
    (1) disjoint constraints
     - 다른 subclass와 공통의 entity가 없는 경우 disjoint라고 한다.
     - attribute-defined이면서 단일 값 속성을 갖는 경우 disjoint subclass이다.
     - diagram에서는 원 안의 d로 표현한다.
    (2) overlap
     - 하나의 entity가 2개 이상의 subclass에 동시에 포함되어 있는 경우 overlap이라고 한다.
     - diagram에서는 원 안의 o로 표현한다.
    (3) total specialization
     - super class의 모든 entity가 특정 subclass의 member가 되는 경우를 의미한다.
     - diagram에서는 ==(double line)으로 표현한다.
    (4) partial specialization
     - 전체 참여의 반대. super class의 entity의 일부반 subclass의 member가 되는 경우
  • insertion & deletion rules for specialization / generalization
    - superclass의 entity를 삭제할 경우, subclass에서도 삭제된다.
    - superclass에 entity를 추가할 경우, predicate-defined subclass에도 추가된다.
    - total specialization의 superclass에 entity를 추가할 경우, 적어도 한개 이상의subclasss에 추가된다.
  • Specialization hierarchies & lattices
    - hierarchy : single inheritance(in java)
    - lattice : multiple inheritance(in cpp..)
  • Top-down || Bottom-up conceptual design
    - Top-down : successive specialization
    - Bottom-up : successive generalization
    - and combination of two 

4. Modeling of UNION Types Using Categories

  • Union type(=category)
    - 사용자가 생성한 가상의 class. 다른 entity 개체로부터 임의로 entity collection을 만들고 이를 union이라고 부른다.

참고문헌 : Fundamentals of Database Systems 7th Edition

+ Recent posts