June

1-2) DB 정리

중간 범위

Lec-01-1

데이터베이스 주요 개념

View

Subset of the database

데이터베이스의 하위 집합

Contains virtual data derived from the database files and but is not explicitly stored

데이터베이스 파일에서 파생되었지만 명시적으로 저장되지 않은 가상 데이터를 포함

Schema

A schema is a description of the data interface to the database

스키마는 데이터베이스에 대한 데이터 인터페이스의 설명

1. External Schema (View)

What the application programs and user see

응용프로그램과 사용자가 보는 내용

May differ for different users of the same database

동일한 데이터베이스의 사용자마다 다를 수 있음

2. Conceptual Schema

Description of the logical structure of all data in the database

데이터베이스에 있는 모든 데이터의 논리적 구조에 대한 설명

3. Physical Schema

Description of physical aspects (selection of files, devices, storage algorithms, etc.)

물리적 측면에 대한 설명(파일 선택, 장치, 저장 알고리즘 등)

Instance

Is a database that conforms to a given schema

주어진 스키마에 맞게 데이터를 저장한 데이터베이스 상태

Transaction

Every application may think they are the sole application accessing the data. The DBMS guarantees correct execution.

모든 응용프로그램은 자신이 데이터에 액세스하는 유일한 응용프로그램이라고 생각할 수 있음. DBMS는 정확한 실행을 보장함

Recovery

Whenever the DBMS acknowledges a data item was stored in the database, then it won't disappear due to crash/power failure/..

DBMS가 데이터베이스에 데이터 항목이 저장되었음을 확인할 때 충돌/전원 장애로 인해 항목이 사라지지 않음

→ 이러한 정의 중에 단답형, 서답형으로 문제 출제(24중간)

Lec-01-2

데이터베이스 (Database)

Collection of related data

연관된 데이터의 집합
  • Represents some aspect of the real world, sometimes called the miniworld or the universe of discourse (UoD)
    현실 세계의 특정 측면을 나타냄 (미니월드 또는 UoD라고 불림)
  • A logically coherent collection of data
    논리적으로 일관성 있는 데이터의 집합
  • Designed, built, and populated with data for a specific purpose
    특정 목적을 위해 설계, 구축되고 데이터로 채워짐

DBMS (Database Management System)

A collection of programs that enables users to create and maintain a database

사용자가 데이터베이스를 생성하고 유지하는 데 필요한 프로그램들의 집합
  • Database Definition: Specifying the data types, structures, and constraints of data to be stored in the database to ensure data consistency and integrity
    데이터베이스 정의: 데이터베이스에 저장할 데이터 유형, 구조, 제약 조건을 지정하여 데이터의 일관성과 무결성을 보장함
  • Data Creation and Maintenance: Supports users to store, retrieve, modify, and delete data
    데이터 생성 및 유지: 사용자가 데이터를 저장하고 검색하며 수정, 삭제할 수 있도록 지원함

Meta-data

Database definition or descriptive information

데이터베이스 정의나 설명적 정보

Contains information about the characteristics and components of data, including database structure, tables, columns, data types, and constraints

데이터베이스 내의 데이터 구조, 테이블, 열, 데이터 타입, 제약 조건 등 데이터의 특성과 구성요소에 대한 정보를 담고 있음

Query

A command to retrieve specific data from the database

데이터베이스에서 특정 데이터를 검색하는 명령

Queries data according to user requests and returns the desired information

사용자 요청에 따라 데이터를 조회하여 원하는 정보를 반환함

Transaction

A unit of work that reads from or writes to the database

데이터베이스에서 데이터를 읽거나 쓰는 작업의 단위

Groups multiple operations and processes them as a single unit of work

여러 연산을 묶어 하나의 작업으로 처리함

Lec-01-3

데이터베이스의 목적

Keep track of things

다양한 정보를 체계적으로 추적하고 관리하는 것

Unlike lists or spreadsheets, databases can store complex information beyond simple lists

리스트나 스프레드시트와는 달리 단순한 리스트 이상의 복잡한 정보를 저장할 수 있음

리스트의 단점

Redundancy (중복성)

In lists, each row exists independently, so the same information can be entered multiple times

목록에서는 각 행이 독립적으로 존재하여 같은 정보가 여러 번 입력될 수 있음

Multiple Themes (여러 가지 주제)

Each row contains information on multiple topics together, meaning other topics' information must also be stored simultaneously to obtain the desired data

각 행에 여러 주제의 정보가 함께 포함되어, 특정 정보가 필요할 때 다른 주제의 정보도 동시에 저장되어 있어야만 원하는 데이터를 얻을 수 있음

Other Issues

Deletion, update, and insertion problems

삭제, 업데이트, 삽입 문제

Relational Databases (관계형 데이터베이스)

A self-describing collection of related tables

자기 서술적인 관련 테이블들의 집합
  • Relational databases use a table structure, where each topic is stored in a separate table
    관계형 데이터베이스는 테이블 구조로, 각 주제는 별도의 테이블에 저장됨
  • Relational databases separate various topics into multiple tables
    관계형 데이터베이스는 다양한 주제들을 여러 개의 테이블로 분리함
  • Each table can establish relationships with others when necessary to connect data, ensuring the same information is not duplicated across multiple tables and is clearly organized
    각각의 테이블은 필요한 경우 서로 관계를 맺어 데이터를 연결하여 동일한 정보가 여러 테이블에 중복되지 않고 명확하게 정리됨

SQL

A language for creating databases and tables

데이터베이스와 테이블을 생성하기 위한 언어

데이터베이스 시스템의 4가지 구성요소

Users, Database Application, DBMS, Database

사용자, 데이터베이스 애플리케이션, DBMS, 데이터베이스

Lec-02-1

Entity

Something of importance to a user that needs to be represented in a database

데이터베이스에 표시해야 하는 사용자에게 중요한 사항

Relation

Two-dimensional table that has specific characteristics

특정 특성을 가진 2차원 테이블

Below are examples of non-relational tables:

Key

One (or more) columns of a relation that is (are) used to identify a row

행을 식별하는 데 사용되는 relation의 하나 이상의 열

Unique Key (고유 키)

Data value is unique for each row. The key will uniquely identify a row

데이터 값은 각 행에 대해 고유함. 키는 행을 고유하게 식별

Nonunique Key (비고유 키)

Data value may be shared among several rows. The key will identify a set of rows

데이터 값은 여러 행 간에 공유될 수 있음. 키가 일련의 행을 식별

Composite Key (복합 키)

Contains two or more attributes. For a key to be unique, it must often become a composite key

두 개 이상의 속성이 포함. 키가 고유하려면 복합 키가 되어야 함

Candidate Key (후보 키)

Called 'candidate' because it is a candidate to become the primary key. It is a unique key

주요 키가 될 후보이기 때문에 candidate라고 불림. 고유한 키

Primary Key (기본 키)

A candidate key chosen to be the main key for the relation. If you know the value of the primary key, you will be able to uniquely identify a single row

relation에서 주요 키로 선택한 후보 키. 기본 키의 값을 알고 있으면 한 행을 고유하게 식별할 수 있음

Surrogate Key (대리 키)

Unique, numeric value that is added to a relation to serve as the primary key. Surrogate key values have no meaning to users and are usually hidden on forms, queries and reports. A surrogate key is often used in place of a composite primary key

relation에 추가된 기본 키로 사용할 고유 숫자 값. 대리 키 값은 사용자에게 의미가 없으며 대개 양식, 쿼리 및 보고서에 숨겨짐. 복합 기본 키 대신 대리 키가 사용되는 경우가 많음

Foreign Key (외래 키)

To preserve relationships, you may need to create a foreign key. A foreign key is a primary key from one table placed into another table. The key is called a foreign key in the table that received the key

관계를 보존하려면 외래 키를 생성해야 할 수 있음. 외래 키는 한 테이블에서 다른 테이블에 배치된 기본 키. 키를 받은 테이블에서 외래 키라고 함

Referential Integrity (참조 무결성)

외래 키의 모든 값이 반드시 기존의 primary key 값과 일치해야 함

NULL Value (널 값)

Represents a state where data has not been entered. A null value does not simply mean empty data, but means the data does not exist at all (different from 0)

데이터가 입력되지 않은 상태를 나타냄. 널 값은 단순히 빈 데이터가 아니라 해당 데이터가 아예 존재하지 않음을 의미함 (0과 다름)

Functional Dependency (함수 종속성)

A relationship where one attribute determines the value of another attribute within the same table

한 속성이 같은 테이블 내 다른 속성의 값을 결정하는 관계

For example, given the individual price of a cookie, you can determine the price of a box of 12 cookies

예를 들어, 쿠키의 개별 가격이 주어지면, 12개짜리 쿠키 박스의 가격을 결정할 수 있는 것

Determinants (결정자)

An attribute that determines the value of other attributes in a dependency relationship

종속 관계에서 다른 속성의 값을 결정하는 속성 (예: 쿠키의 개별 가격)

Normalization (정규화)

A process of analyzing a relation to ensure that it is well formed. If a relation is normalized, rows can be inserted, deleted or modified without creating update anomalies

관계가 잘 형성되었는지 확인하기 위해 관계를 분석하는 과정. 관계가 정규화된 경우 업데이트 이상 없이 행을 삽입, 삭제 또는 수정할 수 있음

Lec-03-1 (SQL)

SQL (Structured Query Language)

based on queries in Relational Calculus

→ SQL 문 쓰는거 (주로 join) 시험에 나옴(24중간, 기말)

DDL (Data Definition Language, 데이터 정의 언어)

Used to define the structure of the database

데이터베이스 구조를 정의하는데 사용됨

Common DDL commands include:

  • CREATE: Creates new database objects (tables, indexes, views, etc.)
    sql
    CREATE TABLE EMPLOYEE(
        EmpID Integer NOT NULL, /* 널 값을 가질 수 없는 정수형 */
        EmpName Char(25) NOT NULL, /*널 값을 가질 수 없는 문자열*/
        CONSTRAINT Emp_PK PRIMARY KEY(EmpID) /* EmpID열을 primary key로 지정하여 각 EmpID 값이 고유한 값이라는 제약을 걸고 그 제약의 이름을 Emp_PK로 지음*/
    );

    Composite Primary Key(복합 기본 키)

    sql
    CREATE TABLE EMP_SKILL(
        EmpID Integer NOT NULL,
        SkillID Integer NOT NULL,
        SkillLevel Integer NULL,
        CONSTRAINT EmpSkill_PK PRIMARY KEY (EmpID, SkillID), /*EmpID와 SkillID 열을 결합하여 복합 기본 키로 설정함. 이를 통해 EmpID와 SkillID의 조합이 고유하여 중복되지 않음을 보장함.*/	
    CONSTRAINT Skill_FK FOREIGN KEY(SkillID) REFERENCES SKILL(SkillID)
    ON UPDATE CASCADE 
    		/*SkillID를 외래 키로 정의하고 SKILL 테이블의 SkillID를 참조함,
    	  이는 EMP_SKILL 테이블의 SkillID 값이 반드시 SKILL테이블에 존재해야 함을 보장함
    	  또한 UPDATE CASCADE 는 참조하는 테이블에서 기본 키 값이 업데이트 될 때,
        해당 행을 참조하 모든 왜래 키 값도 자동으로 업데이트 됨*/
    );
  • ALTER: Modifies existing database objects
    sql
    ALTER TABLE EMPLOYEE
    ADD CONSTRAINT Emp_PK PRIMARY KEY(EmpID);
    /*EMPLOYEE 테이블에 EmpID를 기본 키로 설정하고, 기본키 제약 조건에 Emp_PK라는 이름을 부여함*/
  • DROP: Deletes database objects
    sql
    -	DROP TABLE EMPLOYEE;

DML (Data Manipulation Language, 데이터 조작 언어)

Used to manipulate data within the database

데이터베이스 내의 데이터를 조작하는데 사용됨

Common DML commands include:

  • SELECT: Retrieves data from the database

    Select 문 정리

    기본 형식 : select ~ from ~ where

    sql
    SELECT EmpName
    FROM EMPLOYEE
    WHERE EmpID = 2010001;
    /*EMPLOYEE 테이블에서 EmpID가 2010001인 행의 EmpName 값을 조회함*/

    * : 모든 열의 값 ( select * from … : 조건을 만족하는 열의 모든 값을 출력)

    sql
    SELECT * 
    FROM EMPLOYEE 

    distinct : 중복 행을 제거하고 고유한 값만 표시

    sql
    SELECT DISTINCT DeptID
    FROM EMPLOYEE;

    where 문 : 조건문

    sql
    // 부등호, OR, AND
    SELECT EmpName
    FROM EMPLOYEE
    WHERE DeptID < 7
    OR DeptID > 12;
    sql
    // IN
    SELECT EmpName
    FROM EMPLOYEE
    WHERE DeptID IN (4, 8, 9);
    sql
    // NOT IN
    SELECT EmpName
    FROM EMPLOYEE
    WHERE DeptID NOT IN (4, 8, 9);
    sql
    // BETWEEN AND
    SELECT EmpName
    FROM EMPLOYEE
    WHERE SalaryCode BETWEEN 10 AND 45;
    sql
    // LIKE
    SELECT EmpID
    FROM EMPLOYEE
    WHERE EmpName LIKE 'Kr%';
    
    SELECT EmpID
    FROM EMPLOYEE
    WHERE Phone LIKE '616-___-____';

    Order by : Select 한 결과를 정렬함

    sql
    SELECT EmpName, DeptID
    FROM EMPLOYEE
    ORDER BY DeptID ASC; /*오름차순*/
    
    SELECT EmpName, DeptID
    FROM EMPLOYEE
    ORDER BY DeptID DESC;  /*내림차순*/

    Count : 행의 개수 계산

    sql
    SELECT COUNT(*) 
    FROM EMPLOYEE 
    WHERE DeptID = 5;

    MAX/AVG/MIN : 행의 최댓값, 평균, 최솟값을 출력함

    sql
    SELECT 
        MAX(Salary) AS MaxSalary,
        MIN(Salary) AS MinSalary,
        AVG(Salary) AS AvgSalary,
        SUM(Salary) AS TotalSalary
    FROM EMPLOYEE
    WHERE DeptID = 5;

    Group by : 특정 열을 기준으로 행을 그룹화하여 집계함

    Having : 그룹화된 데이터에 대한 조건을 적용하여 특정 그룹만 필터링함

    sql
    SELECT DeptID,
           COUNT(*) AS NumOfEmployees
    FROM EMPLOYEE
    GROUP BY DeptID
    HAVING COUNT(*) > 3;
    // where과 having의 차이 : where은 그룹화 전의 조건, having은 후의 조건

    Subqueries

    서브 쿼리는 쿼리의 결과를 다른 쿼리의 입력으로 사용하는 쿼리임, 주 쿼리 안에 중접되어, 주 쿼리가 원하는 조건에 맞게 데이터를 사용할 수 있음

    sql
    SELECT EmpName
    FROM EMPLOYEE
    WHERE DeptID IN
        (SELECT DeptID
         FROM DEPARTMENT
         WHERE DeptName LIKE 'Account%');
    	/*DEPARTMENT 테이블에서 DeptName이 Account 로 시작하는
    	 부서의 직원들의 EmpName을 반환함*/

    Join

    JOIN은 다른 테이블 간의 데이터를 결합하여 관계를 형성하는 방법임, 두 테이블을 결합하여 서로 관련 있는 데이터를 하나의 결과로 표시함

    sql
    SELECT EmpName
    FROM EMPLOYEE AS E, DEPARTMENT AS D
    WHERE E.DeptID = D.DeptID
    AND D.DeptName LIKE 'Account%';
    /* FROM EMPLOYEE AS E, DEPARTMENT AS D : EMPLOYEE 테이블을 E라는 별칭으로,
     DEPARTMENT 테이블을 D라는 별칭으로 지정하여 두 테이블을 조인함. 
     WHERE E.DeptID = D.DeptID: EMPLOYEE 테이블의 DeptID와
     DEPARTMENT 테이블의 DeptID가 일치하는 행들만 선택함. 
     이는 두 테이블 간의 관계를 형성함.
     AND D.DeptName LIKE 'Account%': DEPARTMENT 테이블에서 
     DeptName이 'Account'로 시작하는 부서에 해당하는 데이터만 필터링함.
    */

    Subquery와 Join의 두 코드는 서로 같은 의미의 코드임

    Join … on : Join을 직접 써서 가독성을 높임 (위의 Join 문에는 Join이 없음)

    sql
    SELECT EmpName
    FROM EMPLOYEE AS E 
    JOIN DEPARTMENT AS D 
    ON E.DeptID = D.DeptID
    WHERE D.DeptName LIKE 'Account%';

    LEFT OUTER JOIN / RIGHT OUTER JOIN LEFT JOIN은 왼쪽 테이블의 모든 데이터를 반환하며, 오른쪽 테이블에 일치하는 데이터가 없는 경우에는 NULL로 채움, RIGHT은 그와 반대임

    sql
    SELECT EmpName
    FROM EMPLOYEE AS E
    LEFT JOIN DEPARTMENT AS D
    ON E.DeptID = D.DeptID
    AND D.DeptName LIKE 'Account%';

  • INSERT: Adds new records to a table
    sql
    INSERT INTO EMPLOYEE VALUES(91, 'Smither', 12);
    /* EMPLOYEE 테이블에 전체 열 값을 삽입함*/
    INSERT INTO EMPLOYEE (EmpID, SalaryCode) VALUES (62, 11);
    /* EmpID와 SalaryCode 열만 지정하여 값을 삽입함*/
  • UPDATE: Modifies existing records
    sql
    UPDATE EMPLOYEE
    SET Phone = '791-555-1234'
    WHERE EmpID = 29;
    /*29번 EmpID를 가진 EMPLOYEE의 Phone 열을 바꿈*/
    
    UPDATE EMPLOYEE
    SET DeptID = 44
    WHERE EmpName LIKE 'Kr%';
    /*EmpName이 Kr로 시작하는 행들의 DeptID 열을 44로 바꿈*/
  • DELETE: Removes records from a table
    sql
    DELETE FROM EMPLOYEE
    WHERE EmpID = 29;
    /*EmpID가 29인 모든 행을 삭제함*/
    
    DELETE FROM EMPLOYEE
    WHERE EmpName LIKE 'Kr%';
    /*EmpName이 Kr로 시작하는 모든 행을 삭제함*/

DCL (Data Control Language, 데이터 제어 언어)

Used to control access to data in the database

데이터베이스의 데이터에 대한 접근을 제어하는데 사용됨
  • GRANT: Gives permissions
    권한 부여
  • REVOKE: Removes permissions
    권한 회수

// 외전

ALTER & DROP 으로 제약 삭제하기

sql
ALTER TABLE EMPLOYEE DROP CONSTRAINT EmpFK;

EMPLOYEE 테이블에서 EmpFK라는 제약을 드롭하여 제거함

CHECK 제약 CHECK 를 사용하여 열 값이 지정된 조건을 만족해야 하도록 설정할 수 있음

sql
ALTER TABLE PROJECT
ADD CONSTRAINT PROJECT_Check_Dates
CHECK (StartDate < EndDate);

조건을 만족시키지 않는 데이터를 삽입하려고 할 때 오류를 발생시켜 데이터의 무결성을 유지함

Lec-03-2

Set Operation

operations that allow us to combine or compare two relations

UNION

sql
(SELECT pubid FROM book) 
UNION
(SELECT pubid FROM journal);
/*모든 책과 저널의 pubid가 나옴*/

EXCEPT

sql
(SELECT pubid FROM publication)
EXCEPT
(SELECT pubid FROM article);
/*publication 중 article이 아닌 책의 pubid가 나옴*/

VIEW

sql
CREATE VIEW bookorjournal AS
    (SELECT pubid FROM book)
    UNION
    (SELECT pubid FROM journal);
/* bookorjournal이라는 view 생성*/
SELECT title
FROM publication, bookorjournal
WHERE publication.pubid = bookorjournal.pubid;
/*위에서 만든 view 이용*/

→ View 만들기 시험에 나옴(24중간, 기말)

sub query를 이용한 inline view(위 코드와 내용 같음)

sql
SELECT title
FROM publication,
     (SELECT pubid FROM book
      UNION
      SELECT pubid FROM journal) AS bj
WHERE publication.pubid = bj.pubid;

Lec-03-3

Relational Database

A set of relations

관계들의 집합

Relation

A set of tuples or a set of rows

튜플의 집합 또는 행의 집합

Instance (인스턴스)

A table consisting of rows and columns

행과 열로 이루어진 테이블

Schema (스키마)

Specifies name of relation, plus name and type of each column

관계의 이름과 각 열의 이름 및 데이터 유형을 정의함

Example:

sql
Students(sid: string, name: string, login: string, age: integer, gpa: real)

This schema specifies the structure of the Students table and defines the data types

이 스키마는 Students 테이블의 구조를 지정하고, 데이터의 유형을 정의하고 있음

Integrity Constraints (무결성 제약 조건)

A condition that must be true for any instance of the database

데이터베이스 내 모든 인스턴스에 대해 참이어야 하는 조건
sql
CREATE TABLE Students (
    sid CHAR(10),
    age INTEGER CHECK (age >= 0 AND age <= 150),  ← IC: 나이는 0~150
    gpa REAL CHECK (gpa >= 0.0 AND gpa <= 4.0),  ← IC: GPA는 0~4
    PRIMARY KEY (sid)                             ← IC: sid는 고유
);

올바른 데이터 (IC 만족): sid='001', age=20, gpa=3.8

잘못된 데이터 (IC 위반): sid='002', age=-5, gpa=5.0 (나이 음수, GPA 초과)

Legal Instance of a Relation

Is one that satisfies all specified ICs

합법적인 인스턴스란 모든 무결성 제약 조건을 만족하는 상태의 관계를 의미함

Primary Key Constraints (기본 키 제약 조건)

A set of fields is a key for a relation

관계에서 필드들의 집합이 키가 된다.

1. Uniqueness Condition (유일성 조건)

No two distinct tuples can have same values in all key fields

테이블에서 두 개의 서로 다른 튜플은 모든 키 필드에서 같은 값을 가질 수 없다

2. Minimality Condition (최소성 조건)

This is not true for any subset of the key

기본 키는 최소한의 필드 집합으로 이루어져야 한다

Super Key (슈퍼 키)

A key that satisfies condition 1 but not condition 2

유일성 조건은 만족하나 최소성 조건은 만족하지 않는 키

Primary Key (기본 키)

A super key consisting of the minimal set of fields

슈퍼 키 중 최소한의 필드 집합으로 이루어짐

Primary Key and Candidate Key

Possibly many candidate keys, one of which is chosen as the primary key

많은 후보 키 중에서 어떤 하나는 기본 키로 지정된다

Foreign Keys (외래 키)

Must correspond to primary key of the second relation

참조하는 테이블의 기본 키와 대응되어야 한다

Referential Integrity (참조 무결성)

Is a constraint that ensures a foreign key's referenced value always exists in the target table

참조 무결성은 외래 키가 참조하는 값이 항상 참조 대상 테이블에 존재하도록 보장하는 제약 조건이다

Weak Entity (약한 개체)

Can be identified uniquely only by considering the primary key of another entity

다른 개체의 기본 키를 함께 고려해야만 고유하게 식별될 수 있는 개체

A weak entity depends on a strong entity (owner entity) for its existence and identification

약한 개체는 존재와 식별을 위해 강한 개체(소유 개체)에 의존함

예시

Logical DB Design: ER to Relational Model 변환

ER 다이어그램 기호 정리

사각형

Strong Entity - 독립적으로 존재 가능한 엔티티

이중(굵은)사각형

Weak Entity - Owner 없이 식별 불가능한 엔티티

타원

일반 Attribute - 엔티티의 속성

밑줄

Primary Key - 기본키 속성

다이아몬드

일반 Relationship - Strong Entity들 간의 관계

이중(굵은)다이아몬드

Identifying Relationship - Strong-Weak Entity 간의 식별 관계

Partial Participation - 부분 참여 (일부만 참여)

굵은 선

Total Participation - 전체 참여 (모두 참여 필수)

1. Entity Sets → Tables

가장 기본적인 변환, Entity Set을 그대로 테이블로 만든다.

sql
CREATE TABLE Employees
(ssn CHAR(11), // 밑줄 쳐진게 PK
name CHAR(20),
lot INTEGER,
PRIMARY KEY (ssn))

2. Relationship Sets → Tables

Partial Participation (부분 참여)

정의: 일부 entity만 relationship에 참여해도 됨

의미 예시:

  • "일부 직원만 부서를 관리한다" (모든 직원이 매니저는 아님)
  • "일부 부서만 프로젝트를 진행한다"
  • 주로 얇은 선으로 표기됨

Total Participation (전체 참여)

정의: 모든 entity가 반드시 relationship에 참여해야 함

의미 예시:

  • "모든 부서는 반드시 매니저가 있어야 한다"
  • "모든 직원은 반드시 1개 부서에 소속되어야 한다"
  • 주로 굵은 선으로 표기됨

Works-in

sql
CREATE TABLE Works_In(
    ssn CHAR(1),
    did INTEGER,
    since DATE,
    PRIMARY KEY (ssn, did),
    FOREIGN KEY (ssn) REFERENCES Employees,
    FOREIGN KEY (did) REFERENCES Departments
)

1. 어떤 관계?

  • Employees와 Departments 사이의 Many-to-Many 관계
  • "직원들이 부서에서 일한다"

2. Primary Key = (ssn, did)

  • 왜 두 개를 조합?
    • 한 직원이 여러 부서에서 일할 수 있음
    • 한 부서에 여러 직원이 있을 수 있음
    • 따라서 "어떤 직원 + 어떤 부서" 조합만이 고유함

3. Superkey 형성:

  • {ssn, did}가 이 relation의 superkey
  • 두 Foreign Key의 조합

Manages

방법 1.

sql
CREATE TABLE Manages(
    ssn CHAR(11),
    did INTEGER,
    since DATE,
    PRIMARY KEY (did),
    FOREIGN KEY (ssn) REFERENCES Employees,
    FOREIGN KEY (did) REFERENCES Departments
)

1. 왜 Primary key가 (did)인가?

  • 한 부서는 최대 1명의 매니저만 가짐
  • did 값 하나당 ssn도 하나만 존재
  • 따라서 did만으로 row를 고유하게 식별 가능

방법 2.

sql
CREATE TABLE Dept_Mgr(
    did INTEGER,
    dname CHAR(20),
    budget REAL,
    ssn CHAR(11),                  -- 매니저 정보를 여기 통합
    since DATE,
    PRIMARY KEY (did),
    FOREIGN KEY (ssn) REFERENCES Employees
)

장점:

  • 테이블 1개 감소
  • JOIN 불필요
  • 성능 향상

조건:

  • Many-to-One 또는 One-to-One 관계일 때만 가능

Weak Entities

sql
CREATE TABLE Dep_Policy (
pname CHAR(20),
age INTEGER,
cost REAL,
ssn CHAR(11) NOT NULL,
PRIMARY KEY (pname, ssn),
FOREIGN KEY (ssn) REFERENCES Employees,
ON DELETE CASCADE)

자신만의 key로는 고유하게 식별할 수 없는 entity

핵심 특징:

  • Owner Entity의 key가 반드시 필요
  • 독립적으로 존재할 수 없음
  • Owner가 삭제되면 같이 삭제되어야 함
  • 주로 굵은 사각형으로 표기됨

ISA Hierarchies (상속 계층)

“일용직이면서 계약직일 수 있나?” → 없다.

ISA = “is a” (단일 조건)

방법 1: 3개 테이블 (General Approach)

sql
-- 부모 테이블
CREATE TABLE Employees (
    ssn CHAR(11),
    name CHAR(20),
    lot INTEGER,
    PRIMARY KEY (ssn)
);

-- 자식 테이블 1
CREATE TABLE Hourly_Emps (
    ssn CHAR(11),
    hourly_wages REAL,
    hours_worked INTEGER,
    PRIMARY KEY (ssn),
    FOREIGN KEY (ssn) REFERENCES Employees
        ON DELETE CASCADE
);

-- 자식 테이블 2
CREATE TABLE Contract_Emps (
    ssn CHAR(11),
    contractid INTEGER,
    PRIMARY KEY (ssn),
    FOREIGN KEY (ssn) REFERENCES Employees
        ON DELETE CASCADE
);

방법 2: 2개 테이블 (Alternative Approach)

sql
-- 부모 속성을 포함한 자식 테이블 1
CREATE TABLE Hourly_Emps (
    ssn CHAR(11),
    name CHAR(20),          
    lot INTEGER,           
    hourly_wages REAL,
    hours_worked INTEGER,
    PRIMARY KEY (ssn)
);

-- 부모 속성을 포함한 자식 테이블 2
CREATE TABLE Contract_Emps (
    ssn CHAR(11),
    name CHAR(20),          
    lot INTEGER,             
    contractid INTEGER,
    PRIMARY KEY (ssn)
);

Ternary Relationship

3개의 Entity가 동시에 참여하는 하나의 Relationship

2. Binary vs Ternary 비교

Bad Design: 3개의 Binary Relationship

시나리오: 직원이 보험으로 부양가족을 커버

    Employees
      /   \
     /     \
Covers   Purchaser
   /         \
  /           \
Dependents   Policies
     \         /
      \       /
    Beneficiary

3개의 Binary 관계:

  1. Employees --Covers--> Dependents (직원이 부양가족을 커버)
  2. Employees --Purchaser--> Policies (직원이 보험 구매)
  3. Policies --Beneficiary--> Dependents (보험이 부양가족 커버)

문제점:

데이터:
1. Alice --Covers--> Tom
2. Alice --Purchaser--> 보험A
3. 보험A --Beneficiary--> Tom

질문: "Alice가 '보험A'로 'Tom'을 커버하는가?"
→ 답을 알 수 없음

가능한 해석:
- Alice가 보험A 구매했고, Tom을 커버한다
- 하지만 Alice가 '보험B'로 Tom을 커버하는지?
- 보험A로 'Jane'을 커버하는지?
→ 3자 관계가 명확하지 않음

Better Design: Ternary Relationship

        Employees
            |
        Purchaser
            |
        Policies
            |
       Beneficiary
            |
        Dependents

하나의 Ternary 관계: "직원이 특정 보험으로 특정 부양가족을 커버"

명확한 의미:

sql
(Alice, 보험A, Tom) = "Alice가 보험A로 Tom을 커버"
(Alice, 보험B, Jane) = "Alice가 보험B로 Jane을 커버"

Lec-03-4 (Relational Algebra)

Relational Model

All information is organized in relations

Relational Algebra (관계 대수)

관계 대수는 연산자들의 집합으로 구성됨

관계 대수는 폐쇄적임

  • 각 연산자는 0개 이상의 관계를 입력받음
  • 각 연산자는 입력 관계를 기반으로 단일 출력 관계를 정의함
  • 관계 연산자들을 조합하여 기존 관계로부터 새로운 관계를 정의하는 표현식을 만들 수 있음

Notation (표기법)

  • R: 관계 이름 (테이블)
  • E: 관계 대수 표현식 (연산을 적용한 결과)

Selection :

σcondition(E)\sigma_{condition}(E)

주어진 조건을 만족하는 튜플들을 반환

  • 결과 스키마는 E의 스키마와 동일함
  • 결과 인스턴스는 조건을 만족하는 E의 튜플들의 부분집합을 포함함

예시:  - Salary가 100000보다 큰 직원들을 선택

σSalary>100000(Employee)\sigma_{\text{Salary} > 100000}(Employee)

Projection :

πattributes(E)\pi_{attributes}(E)

특정 열들을 선택하고 중복을 제거함

  • 결과 스키마는 지정된 속성들만 포함함
  • 결과 인스턴스는 E만큼의 튜플을 가질 수 있지만, 중복은 제거됨

예시:

πLastName,HireDate(σSalary>100000(Employee))\pi_{LastName,HireDate}(\sigma_{\text{Salary} > 100000}(Employee))

 - Salary가 100000보다 큰 직원들의 LastName과 HireDate만 선택

Cartesian Product (카티션 곱): E₁ × E₂

E₁과 E₂의 모든 속성을 결합

  • 결과 스키마는 E₁의 모든 속성과 E₂의 모든 속성을 가짐
  • 결과 인스턴스는 E₁과 E₂의 튜플 쌍(각 표현식 결과에서 하나씩)마다 하나의 튜플을 포함함
  • 교차곱 또는 카티션 곱이라고도 불림
  • E₁과 E₂가 공통 속성을 가질 때 이름 변경이 필요함

→ 표 주고 곱하는거 나왔던거같음(24중간)

Cross Product 예시:

R:

AAABBB
a1b1
a2b2
a3b3

S:

CCCDDD
c1d1
c2d2

R × S:

AAABBBCCCDDD
a1b1c1d1
a2b2c1d1
a3b3c1d1
a1b1c2d2
a2b2c2d2
a3b3c2d2

Join Operations (조인 연산)

Conditional Join (조건 조인):

E1conditionE2E_1⋈_{condition}E_2

조건을 만족하는 튜플들을 조인

  • 다음과 동치: σcondition(E₁ × E₂)
  • 특수한 경우: 동등 조인 (조건이 등호일 때)

예시: 

Proj(RespEmp=EmpNo)EmpProj ⋈_{(RespEmp=EmpNo)} Emp

- Project와 Employee를 RespEmp=EmpNo 조건으로 조인

Natural Join (자연 조인):

E1E2E_1 ⋈ E_2

두 관계의 공통 속성을 기준으로 조인

E₁ ⋈ E₂의 결과는 다음 단계로 형성될 수 있음:

  1. E₁과 E₂의 카티션 곱을 형성 (중복 속성 이름 변경)
  2. 교차곱에서 스키마 E₁과 E₂에 공통인 모든 속성 쌍에 대해 일치하는 값이 없는 튜플들을 제거
  3. 중복 속성을 프로젝션으로 제거

공통 속성이 없으면, 이것은 단순히 곱셈임


Set-based Relational Operators (집합 기반 관계 연산자)

Union (합집합): R ∪ S

두 관계의 튜플들을 결합

  • R과 S의 스키마는 "합집합 호환"이어야 함
  • 결과는 R 또는 S 또는 둘 다에 나타나는 모든 튜플을 포함함

Difference (차집합): R − S

R에는 있지만 S에는 없는 튜플들을 반환

  • R과 S의 스키마는 "합집합 호환"이어야 함
  • 결과는 R에 나타나지만 S에는 나타나지 않는 모든 튜플을 포함함

Intersection (교집합): R ∩ S

두 관계 모두에 나타나는 튜플들을 반환

  • R과 S의 스키마는 "합집합 호환"이어야 함
  • 결과는 R과 S 모두에 나타나는 모든 튜플을 포함함

Union Compatible (합집합 호환)

두 관계가 다음 조건을 만족하면 합집합 호환임:

  • 같은 수의 필드
  • '대응하는' 필드들이 같은 타입을 가짐

Division (나눗셈): E₁ / E₂

"모든"을 포함하는 쿼리에 사용됨

E₂의 모든 튜플과 연관된 E₁의 튜플들을 반환

예시 시나리오: "CS 학과에서 제공하는 모든 과목을 수강한 학생을 찾기”


Algebraic Equivalence (대수적 동치성)

여러 관계 대수 표현식이 같은 결과를 생성할 수 있음. 쿼리 최적화는 이러한 동치성을 사용하여 효율적인 실행 계획을 찾음

다음 표현식들은 모두 동치임:

  1. π_ProjNo,LastName(σ_DeptNo=E21(σ_RespEmp=EmpNo(E × P)))
  2. π_ProjNo,LastName(σ_DeptNo=E21(E ⋈_RespEmp=EmpNo P))
  3. π_ProjNo,LastName(E ⋈_RespEmp=EmpNo σ_DeptNo=E21(P))
  4. π_ProjNo,LastName((π_LastName,EmpNo(E)) ⋈_RespEmp=EmpNo (π_ProjNo,RespEmp(σ_DeptNo=E21(P))))

Relational Completeness (관계 완전성)

관계 대수만큼 최소한 표현력이 있는 쿼리 언어는 관계적으로 완전하다고 말함

다음 언어들은 모두 관계적으로 완전함:

  • Safe relational calculus (안전한 관계 미적분)
  • Relational algebra (관계 대수)
  • SQL

SQL은 중복 튜플, 알 수 없는 값, 집계, 정렬 등을 다룰 수 있어 추가적인 표현력을 가짐

→ Relation Algebra 수식 쓰는 문제 나옴(24 중간, 기말)

중간고사 연습문제 + 추가 문제

ITE316 Midterm Sample

True or False

  1. Every table is a relation, but not every relation is a table.

    F

    “Every relation is a table, but not every table is a relation.”

  2. To be considered a composite key, a key must contain at least two attributes.

    T

    To be considered a composite key, a key must contain at least two attributes.

  3. Normalization is the process of removing all functional dependencies from a relation.

    F

    모든 functional dependencies를 지우지는 않는다.

  4. The basic idea of a join is to combine the contents of two or more relations into a new relation.

    T

    The basic idea of a join is to combine the contents of two or more relations into a new relation.

  5. To force the DBMS to remove duplicate rows from the results of a SQL SELECT query, the keyword DISTINCT must be used.

    T

    To force the DBMS to remove duplicate rows from the results of a SQL SELECT query, the keyword DISTINCT must be used.

Multiple Choice

  1. A relational database stores data in the form of:
    • A) lists
    • B) forms
    • C) columns
    • D) tables
    • E) spreadsheets

    D

  2. A relational database is:
    • A) a self-describing collection of related tables
    • B) a collection of forms and reports that support a given purpose
    • C) a library of queries and data files for querying
    • D) a set of applications and the data sets for those applications
    • E) a set of metadata

    A

  3. A primary key is:
    • A) required to be unique
    • B) used to represent rows in relationships
    • C) a candidate key
    • D) used to identify unique rows
    • E) All of the above

    E

  4. A candidate key is:
    • A) required to be unique
    • B) used to represent rows in relationships
    • C) a candidate to be the primary key
    • D) Both A and B
    • E) Both A and C

    E

  5. Given the table STUDENT(StudentID, Name, Advisor), which of the following SQL statements would be used to add new student data to the STUDENT table?
    • A) INSERT DATA STUDENT SET StudentID=123, Name='Jones', Advisor='Smith';
    • B) INSERT INTO STUDENT VALUES (123, 'Jones', 'Smith');
    • C) INSERT INTO STUDENT (New Student Data) VALUES (123, 'Jones', 'Smith');
    • D) INPUT DATA STUDENT SET StudentID=123, Name='Jones', Advisor='Smith';
    • E) INPUT INTO STUDENT (123, 'Jones', 'Smith');

    B


Short Answer

  1. Explain the terms relation, tuple, and attribute.

    • Relation: A table with columns and rows representing data in a relational database.
    • Tuple: A single row in a relation.
    • Attribute: A column of a relation.

SQL

  1. Given the table CUSTOMER(CustID, Name, PhoneNumber, AccountBalance), write the standard SQL query to retrieve the Name and Phone Number of customers with a balance greater than 50.

    sql
    SELECT Name, PhoneNumber
    FROM CUSTOMER
    WHERE AccountBalance > 50;
  2. Given the table CUSTOMER(CustID, Name, PhoneNumber, AccountBalance), write the standard SQL query to retrieve the Name and Phone Number of customers whose name begins with 'S'.

    sql
    SELECT Name, PhoneNumber
    FROM CUSTOMER
    WHERE Name LIKE 'S%';

Functional Dependencies

Consider the following relation: STUDENT (StudentNumber, StudentName, SiblingName, Major)

Assume that the values of SiblingName are the names of all of a given student's brothers and sisters; also assume that students have at most one major.

  1. Show an example of this relation for two students, one of whom has three siblings and the other of whom has only two siblings.

    StudentNumberStudentNameSiblingNameMajor
    1001AliceBobCS
    1001AliceCarolCS
    1001AliceDaveCS
    1002JohnEmmaMath
    1002JohnFrankMath
  2. State the functional dependencies in this relation.

    scss
    StudentNumber → StudentName, Major
    (StudentNumber, SiblingName) → StudentName, Major

SQL (Multi-table Query)

Consider database with the following tables:

  • PRODUCT (pid, pname, manufacturer, color, weight)
  • STORE (sid, sname, address, city, phone)
  • INVENTORY (pid, sid, price, quantity)
  1. Write a SQL query that gives a list of store names, addresses, and cities of all stores that have red iPods in stock?

    sql
    SELECT s.sname, s.address, s.city
    FROM STORE s
    JOIN INVENTORY i ON s.sid = i.sid
    JOIN PRODUCT p ON i.pid = p.pid
    WHERE p.pname = 'iPod'
      AND p.color = 'red'
      AND i.quantity > 0;

Relational Algebra

Schema:

Write a query in the relational algebra for the following: The professor number and name of professors in the 'InformationSystem' department who have taught a student in 'ITE316' whose final grade was less than '80'.

답 (논리만 맞다면 모두 가능)

1.

πpnum,pname(σdept=InformationSystem(professor)pnumσcnum=ITE316grade<80(classcnum,term,sectionmark))π_{pnum, pname} ( σ_{dept='InformationSystem'} (professor) ⋈_{pnum} σ_{cnum='ITE316' ∧ grade < 80} ( class ⋈_{cnum,term,section} mark ) )

2.

πpnum,pname(σdept=InformationSystem(professor)σcnum=ITE316grade<80(classmark)) \pi_{pnum, pname} \big( \sigma_{dept='InformationSystem'} (professor) \bowtie \sigma_{cnum='ITE316' \land grade < 80} (class \bowtie mark) \big)

추가 문제

  1. Integrity Constraints가 무엇인가?

    condition that must be true for any instance of the database

  2. null value의 의미 3가지?

    Unknown, Not Applicable, Not Available

  3. CUSTOMER(CustomerPhone, CustomerName, BalanceAccount)

    통장잔고가 50만 이상인 고객들의 이름과 전화번호를 출력하는 SQL문을 작성하시오.

    sql
    SELECT CustomerName, CustomerPhone FROM CUSTOMER WHERE BalanceAccount >= 500000;
  4. Meta data가 무엇인가?

    Stored by the DBMS in the form of a database catalog or dictionary

  5. Composite key와 Candidate key가 무엇인가?

    Composite key : a key that contains two or more attribute

    Candidate key : called "candidate" because it is a candidate to become the primary key

  6. Fuction of a DBMS (3가지 이상)

    1. create databases
    2. create tables
    3. create supporting structures
    4. read database data
    5. modify database data
    6, maintain database structures7. enforce rules
    8. control concurrency
    9. provide security
    10. perform backup and recovery
    
  7. Schema

7-1. ‘ABA232’ ‘ITE312’를 둘 다 듣지 않은 3학년 학생 snum, sname relation algebra 작성

πsnum,sname(σyear=3(Student)πsnum,sname(Studentσcnum=ABA232cnum=ITE312(Class)))π_{snum, sname} ( σ_{year=3} (Student) - π_{snum, sname} ( Student ⋈ σ_{cnum='ABA232' ∨ cnum='ITE312'} (Class) ) )

7-2. 정보시스템학과 교수이면서 ‘ITE312’에서 80점 이하를 받은 학생을 가르친 교수 pnum, pname relation algebra 작성

πpnum,pname(σdname=정보시스템학(Professor)σcnum=ITE312grade80(ClassMark))π_{pnum, pname} ( σ_{dname='정보시스템학과'} (Professor) ⋈ σ_{cnum='ITE312' ∧ grade≤80} (Class⋈Mark) )
  1. Company 데이터베이스를 사용하기 위한 명령어?

sql
USE Company;
  1. table
    sql
    -- 1. 학생 테이블
    CREATE TABLE Students (
        sid CHAR(5),
        name VARCHAR(50),
        major VARCHAR(30),
        year INTEGER,
        PRIMARY KEY (sid)
    );
    
    -- 2. 교수 테이블
    CREATE TABLE Professors (
        pid CHAR(5),
        name VARCHAR(50),
        department VARCHAR(30),
        salary INTEGER,
        PRIMARY KEY (pid)
    );
    
    -- 3. 과목 테이블
    CREATE TABLE Courses (
        cid CHAR(5),
        title VARCHAR(100),
        credits INTEGER,
        department VARCHAR(30),
        PRIMARY KEY (cid)
    );
    
    -- 4. 수강 테이블 (Students - Courses)
    CREATE TABLE Enrolls (
        sid CHAR(5),
        cid CHAR(5),
        semester VARCHAR(10),
        grade CHAR(2),
        PRIMARY KEY (sid, cid, semester),
        FOREIGN KEY (sid) REFERENCES Students,
        FOREIGN KEY (cid) REFERENCES Courses
    );
    
    -- 5. 강의 테이블 (Professors - Courses)
    CREATE TABLE Teaches (
        pid CHAR(5),
        cid CHAR(5),
        semester VARCHAR(10),
        classroom VARCHAR(20),
        PRIMARY KEY (pid, cid, semester),
        FOREIGN KEY (pid) REFERENCES Professors,
        FOREIGN KEY (cid) REFERENCES Courses
    );

9-1. Nested query를 사용하여 BOB의 수강과목의 ID와 강의 이름, 수강 학기, 시험 점수를 모두 출력하는 쿼리를 작성하시오.

sql
SELECT C.cid, C.title, E.semester, E.grade
FROM Courses C
WHERE C.cid IN (
    SELECT E.cid
    FROM Enrolls E
    WHERE E.sid = (
        SELECT S.sid
        FROM Students S
        WHERE S.name = 'Bob'
    )
);

9-2. Join을 사용하여 Database Systems 과목을 수강하고 성적이 A 이상인 학생의 이름과 성적을 모두 출력하는 쿼리를 작성하시오.

sql
SELECT S.name, E.grade
FROM Students S
JOIN Enrolls E ON S.sid = E.sid
JOIN Courses C ON E.cid = C.cid
WHERE C.title = 'Database Systems'
  AND E.grade IN ('A+', 'A');

추가 추가 문제

  1. Which SQL statement is used to insert new rows into a table?

    Answer _____

    A) INSERT INTO table_name VALUES (...);

    B) UPDATE table_name SET ...;

    C) DELETE FROM table_name;

    D) SELECT * FROM table_name;

    E) ADD RECORD table_name;

    A

  1. In SQL, which clause is used to filter the results after grouping?

    Answer _____

    A) WHERE

    B) HAVING

    C) ORDER BY

    D) GROUP BY

    E) FILTER

    B

  2. Which of the following is not a Data Definition Language (DDL) command in SQL?

    Answer _____

    A) SELECT

    B) CREATE

    C) ALTER

    D) DROP

    E) TRUNCATE

    A

  3. Define referential integrity. How does a foreign key constraint enforce referential integrity?

    Ensures that foreign key values in one table match primary key values in another table.

    Enforced by foreign key constraints; they prevent inserting or deleting records that would break cross-table consistency.

  4. Given the tables
    sql
    CLIENT(ClientID, Name, City)
    PURCHASE(PurchaseID, ClientID, PurchaseDate, Amount)

    write the standard SQL query to retrieve the Name and City of clients who have made at least one purchase.

    sql
    SELECT c.Name, c.City
    FROM CLIENT c
    JOIN PURCHASE p ON c.ClientID = p.ClientID;
  5. Schema notes :
    sql
    INSTRUCTOR(ID, name, dept_name, salary)
    
    DEPARTMENT(dept_name, building, budget)
    
    STUDENT(ID, name, dept_name, tot_cred)
    
    TAKES(ID, course_id, sec_id, semester, year, grade)
    
    COURSE(course_id, title, dept_name)
    
    ORDERS(OrderID, CustomerID, OrderDate)
    
    ORDERITEM(OrderID, ProductID, Quantity)
    
    PRODUCT(ProductID, Name, Category)

    6-1.

    Using INSTRUCTOR and DEPARTMENT, write a SQL query that returns each dept_name together with the average salary for that department, but only include departments whose average salary is greater than 80,000. Use GROUP BY and HAVING.

    Write the standard SQL query.

    sql
    SELECT dept_name, AVG(salary) AS avg_salary
    FROM INSTRUCTOR
    GROUP BY dept_name
    HAVING AVG(salary) > 80000;

    6-2.

    Using INSTRUCTOR, write a SQL query to return the name(s) of instructor(s) who earn the maximum salary.

    sql
    SELECT name
    FROM INSTRUCTOR
    WHERE salary = (SELECT MAX(salary) FROM INSTRUCTOR);

    6-3.

    Using STUDENT, COURSE, and TAKES, write a SQL query that finds all students(ID and name) who have taken every course offered by the 'Biology' department. Use a NOT EXISTS (or equivalent NOT IN) pattern with a nested subquery, following the pattern shown in the lecture slides.

    Write the standard SQL query.

    sql
    SELECT s.ID, s.name
    FROM STUDENT s
    WHERE NOT EXISTS (
      SELECT *
      FROM COURSE c
      WHERE c.dept_name = 'Biology'
        AND c.course_id NOT IN (
          SELECT t.course_id
          FROM TAKES t
          WHERE t.ID = s.ID
        )
    );

    6-4.

    Using STUDENT and TAKES, write a SQL query that returns ID and name of students who have not taken any course. Use an outer join pattern (for example, NATURAL LEFT OUTER JOIN or LEFT OUTER JOIN ... ON) and a WHERE clause to detect NULL in the TAKES side.

    Write the standard SQL query.

    sql
    SELECT s.ID, s.name
    FROM STUDENT s
    LEFT OUTER JOIN TAKES t ON s.ID = t.ID
    WHERE t.course_id IS NULL;

    6-5.

    Using PRODUCT, ORDERITEM, and ORDERS, write a SQL query that lists each ProductID and the number of distinct orders that include that product, and then returns only those products that appear in more than 10 distinct orders. Use GROUP BY and HAVING.

    Write the standard SQL query.

    sql
    SELECT p.ProductID, COUNT(DISTINCT oi.OrderID) AS order_count
    FROM PRODUCT p
    JOIN ORDERITEM oi ON p.ProductID = oi.ProductID
    GROUP BY p.ProductID
    HAVING COUNT(DISTINCT oi.OrderID) > 10;

참고

FirstOrderLogic 나오는 기호 알아야 함

몽고DB 명령어? 단답형으로 나왔었음 (24중간)

기말 범위

Lec-05-1 (ER)

SQL Views

View란?

  • 실제 데이터를 저장하지 않는 가상 테이블
  • 다른 테이블이나 다른 뷰를 기반으로 생성됨
  • SELECT 문 결과를 이름으로 저장한 구조

View의 특징

  • 자체적으로 데이터를 가지지 않음
  • SELECT에서 테이블처럼 사용할 수 있음
  • CREATE VIEW 내부에서는 ORDER BY 사용 불가

    → 조회 시 SELECT에서 정렬해야 함

Create view

sql
CREATE VIEW ViewName AS
SELECT ...
FROM ...
WHERE ...
sql
CREATE VIEW ViewName AS 
				{SQL SELECT statement};
				
CREATE VIEW EmployeePhoneView AS
		SELECT FirstName, LastName,
					 Phone AS EmployeePhone
		FROM EMPLOYEE;

Using View

뷰가 만들어지면 FROM에 SELECT를 테이블 처럼 사용가능하다.

sql
SELECT *
FROM EmployeePhoneView
ORDER BY LastName;

View를 사용하는 이유

1. 특정 컬럼/행 숨기기

  • 민감한 정보 보호
  • 예: 부서의 전화번호만 보여주는 View

2. 계산 결과 제공

  • 집계 SUM, AVG 등을 미리 계산하여 View로 제공

3. 복잡한 SQL 숨기기

  • 여러 JOIN이 필요한 복잡한 쿼리를 단순화

4. View 위에 View 생성 (Layering)

  • 가공 단계를 나누어 재사용성을 높임

E-R Model 개념

E-R 모델의 구성 요소

1. Entity (엔티티)

  • 데이터를 저장해야 하는 개체
  • 예: EMPLOYEE, PROJECT

2. Attributes (속성)

  • 엔티티가 갖는 특성
  • 예: ProjectName, StartDate

3. Identifiers (식별자)

  • 엔티티 인스턴스를 구분하는 값
  • 예: EmployeeID, StudentID

Entity Class와 Entity Instance의 차이

Entity Class (엔티티 클래스)

  • 하나의 엔티티가 어떤 구조를 가질지 정의한 틀(template)
  • 테이블의 스키마(구조) 수준에서 “어떤 속성들이 있는가”를 설명
  • 즉, 형태·구조 정의서
  • 예: EMPLOYEE 엔티티 클래스
    • 속성: EmployeeID, Name, Age, Salary

Entity Instance (엔티티 인스턴스)

  • 엔티티 클래스 구조를 실제로 채운 한 개의 데이터(행, row)
  • 실제로 존재하는 구체적 데이터 한 건
  • 예:
    • EmployeeID: 101
    • Name: Alex Kim
    • Age: 25
    • Salary: 3500

이런 하나의 행이 하나의 엔티티 인스턴스

Identifiers 종류

Unique Identifier

  • 모든 인스턴스를 구별할 수 있는 값

Composite Identifier

  • 여러 속성 조합으로 구성
  • 예: OrderNumber + LineItemNumber

Relationships (관계)

Entity는 다른 Entity와 관계로 연결되어 있다.

Binary Relationship (2개 엔티티)

가장 일반적인 형태

예: Employee — works on → Project

1. One-to-One (1:1) 관계

정의

두 엔티티 간에서

한 엔티티 인스턴스가 다른 엔티티 인스턴스 단 하나와만 연결되는 관계

  • A의 한 인스턴스 → B의 한 인스턴스
  • B의 한 인스턴스 → A의 한 인스턴스

즉, 양쪽 모두 “최대 1개“만 연결 가능

특징

  • 두 엔티티를 한 테이블로 합칠 수도 있음
  • 논리적으로만 분리하고 데이터는 거의 1:1 대응될 때 사용
  • 보안·기능적 분리를 위해 테이블을 나누기도 함

2. One-to-Many (1:N) 관계

정의

한 엔티티 인스턴스가 다른 엔티티의 여러 개 인스턴스와 연결될 수 있는 관계

  • A 한 개 → B 여러 개
  • B 한 개 → A 하나만 가능

즉, “부모 1 → 자식 여러 명”

특징

  • 가장 흔한 관계
  • 외래키(FK)는 N(여러 개) 쪽에 저장
  • A가 삭제될 때 B가 영향을 받는 경우가 많음

3. Many-to-Many (N:M) 관계

정의

한 엔티티 인스턴스가 다른 엔티티 인스턴스 여러 개와 연결,

그리고 다른 엔티티 인스턴스도 이 엔티티의 여러 개와 연결될 수 있는 관계

  • A 여러 개 ↔ B 여러 개

특징

  • 관계를 직접 테이블로 표현할 수 없음
  • 반드시 중간 테이블(bridge table, join table) 필요
  • 중간 테이블은 보통 2개의 FK를 합친 복합키를 가짐

Ternary Relationship (3개 엔티티)

예: Supplier — supplies → Item — to → Department

관계의 Cardinality (카디널리티)

Maximum Cardinality

  • 참여 가능한 최대 개수
  • 1 또는 Many

Minimum Cardinality

  • 0 (선택적) 또는 1 (필수)

HAS-A Relationship

정의

HAS-A 관계는 두 엔티티 사이에

“A는 B를 가진다”(A has a B) 라는 의미의 관계를 나타내는 표현이다.

즉, 한 엔티티 인스턴스가 다른 엔티티 인스턴스와 연결되어 있다는 것을 의미한다.


Crow’s Foot 표기법

Weak Entity

정의

  • 스스로는 식별 불가능한 엔티티
  • Strong Entity의 PK를 함께 사용해야 식별 가능

특징

  • ID-dependent인 경우 composite key를 사용
  • Strong Entity 삭제 시 함께 삭제
  • ERD에서 굵은 사각형으로 표시

Identifying Relationship / Non-Identifying Relationship

Identifying Relationship

  • Weak Entity를 식별하는 강한 관계
  • 실선으로 연결

Non-identifying Relationship

  • 일반적인 관계
  • 점선으로 연결

Subtype / Supertype

Supertype

  • 공통 속성을 가진 상위 엔티티

Subtype

  • 더 구체적이고 특정한 엔티티

Discriminator

  • 어떤 subtype인지 구분하는 속성

종류

  • Exclusive: 하나의 subtype만 속할 수 있음
  • Inclusive: 여러 subtype이 가능

Recursive Relationship

정의

엔티티가 자기 자신과 관계를 맺는 경우

예: 직원 — manages → 직원

Heather Sweeney Designs 예제 → 읽어보기

단계별 ERD 개발

  1. 고객 세미나 정보 수집
  2. 초기 ERD 작성
  3. CONTACT 엔티티 추가
  4. CONTACT가 Weak Entity로 재설계
  5. CUSTOMER 속성 보완
  6. INVOICE 엔티티 추가
  7. LINE_ITEM 엔티티 추가
  8. 전체 데이터를 반영한 최종 ERD 완성

이 예제는 현실 요구사항 → ERD → 테이블 구조 로 자연스럽게 변환되는 과정을 보여주는 사례.

Lec-05-2 (ER)

1. Conceptual Modeling (개념적 모델링)

개념적 모델링을 하는 이유

  • 현실 세계의 데이터를 구조화하고 정확하게 표현하기 위해 필요
  • 사용자 요구사항을 데이터 모델 형태로 추상화
  • 데이터베이스 설계의 첫 단계이며, 논리/물리 설계의 기반이 됨
  • 시스템을 만들기 전에 “어떤 데이터를 다룰 것인가?”를 명확히 함

2. E-R Model Overview

E-R 모델이란?

  • 현실 세계의 개체(Entity)와 관계(Relationship)를

    그림(ERD) 으로 표현하는 방식

  • DB 설계에서 가장 널리 사용되는 모델

구성 요소

  1. Entity Sets
  2. Relationships
  3. Attributes
  4. Constraints

3. Basic E-R Modeling

Entity (엔티티)

  • 현실 세계의 객체, 개념, 사람, 사건 등
  • 독립적으로 식별 가능해야 한다.

Entity Set (엔티티 집합)

  • 동일한 타입의 엔티티들의 모음

    예: Students, Employees, Courses

Attribute (속성)

  • 엔티티를 설명하는 정보
  • 예: name, age, address

4. Graphical Representation (ERD 표기)

ERD에서의 기본 요소:

  • 사각형: Entity Set
  • 마름모: Relationship
  • 타원: Attribute
  • 밑줄: Primary Key
  • 다중선 / 단선: 참여 제약

이하 내용은 5-1과 같음, 단 둘 다 그림 알아야함

Lec-06-1

Representing Entities with the Relational Model

엔티티를 관계형 모델로 표현하는 과정

1) 엔티티마다 하나의 Relation 생성

  • Relation(테이블)은 설명적인 이름을 갖는다.
  • 엔티티를 구성하는 속성(attribute)들을 column으로 만든다.

2) Primary Key 지정

  • 각 튜플(행)을 uniquely 식별할 수 있는 속성을 PK로 선택한다.
  • 단일 PK 또는 복합 PK가 될 수 있다.

3) 각 Column의 속성(property) 정의

  • Data Type: CHAR, VARCHAR, INTEGER, REAL 등
  • Null Status: NULL 허용 여부
  • Default Values: 기본값 설정 여부
  • Data Constraints: CHECK, UNIQUE 등 제약 조건

4) Normalization 적용

  • 생성된 Relation은 정규화 규칙(1NF, 2NF, 3NF, BCNF 등)에 따라 분석한다.

Representing an Entity as a Table

Normalization Review: Modification Problems

정규화되지 않은 테이블은 ‘수정 이상(Modification Anomalies)’이라고 불리는 문제들을 겪게 된다.

이 문제들은 데이터의 삽입, 수정, 삭제 과정에서 비정상적인 동작을 유발한다.

1) Insertion Problems (삽입 이상)

  • 새로운 데이터를 테이블에 삽입하기가 어려워지는 문제

2) Modification Problems (수정 이상)

  • 데이터를 수정할 때 여러 행을 동시에 수정해야 하는 문제

3) Deletion Problems (삭제 이상)

  • 특정 데이터를 삭제할 때 원치 않는 다른 데이터까지 함께 사라지는 문제

수정 이상 → 정규화로 해결

Functional Dependency (함수적 종속성)

Functional Dependency란, 하나의 속성 값으로 다른 속성 값을 결정할 수 있는 관계를 의미한다.

이는 같은 relation(테이블) 내부에서 성립하는 개념이다.

예시:

  • ZIP → City, State

    ZIP 코드를 알면 City와 State 값을 찾을 수 있음.

Determinant (결정자)

Determinant란, 다른 속성의 값을 결정하는 역할을 하는 속성을 의미한다.

  • Functional Dependency의 좌변(LHS) 에 위치한 속성
  • 예: ZIP → City 에서 ZIP이 결정자(Determinant)

Candidate Key

Candidate Key란, 테이블 내의 모든 다른 속성을 결정할 수 있는 속성(또는 속성 집합) 을 말한다.

Simple Candidate Key

  • 단일 속성 하나로 이루어진 Candidate Key

Composite Candidate Key

  • 두 개 이상의 속성 조합으로 이루어진 Candidate Key

Normalization

정규화 종류

1) First Normal Form (1NF)

  • 모든 속성 값이 원자값(Atomic Value)을 가져야 한다.
  • 반복 그룹이나 배열 같은 구조 제거.

2) Second Normal Form (2NF)

  • 1NF 만족 +
  • 부분적 종속(Partial Dependency) 제거
  • 즉, 복합키의 일부만으로 다른 속성이 결정되는 상황 제거.

3) Third Normal Form (3NF)

  • 2NF 만족 +
  • 이행적 종속(Transitive Dependency) 제거
  • 키가 아닌 속성이 다른 비키 속성을 결정하지 않아야 함.

4) Boyce-Codd Normal Form (BCNF)

  • 3NF보다 강화된 규칙
  • 모든 Determinant(결정자)는 Candidate Key여야 함.
  • 실무에서 가장 자주 목표로 삼는 정규형.

5) Fourth Normal Form (4NF)

  • BCNF 만족 +
  • 다치 종속(Multi-valued Dependency, MVD) 제거.

6) Fifth Normal Form (5NF)

  • 가능한 모든 조인 종속성(Join Dependency) 해결
  • 관계를 더 이상 의미 있게 분해할 수 없는 상태.

7) Domain/Key Normal Form (DK/NF)

  • 가장 엄격한 정규형
  • 모든 제약이 Domain과 Key에 의해서만 정의되는 상태.

Normalization Example: CUSTOMER 테이블 정규화

원본 테이블

sql
CUSTOMER(CustomerNumber, CustomerName, StreetAddress,
         City, State, ZIP, ContactName, Phone)

주어진 Functional Dependencies

  • ZIP → (City, State)

    ZIP 코드를 알면 City, State를 결정할 수 있음

  • ContactName → Phone

    담당자(ContactName)를 알면 Phone을 결정할 수 있음


정규화 후 테이블

1) CUSTOMER 테이블 (정규화 후)

sql
CUSTOMER(CustomerNumber, CustomerName, StreetAddress, ZIP, ContactName)
  • City, State 제거
  • Phone 제거
  • ZIP만 저장하면 City, State는 ZIP 테이블에서 참조 가능
  • ContactName만 저장하고 Phone은 CONTACT 테이블에서 참조

2) ZIP 테이블

ZIP(ZIP, City, State)

역할:

  • ZIP 코드가 결정자(Determinant)
  • City, State의 중복 제거
  • ZIP 변경 시 모든 관련 City/State가 자동으로 일관성 유지

3) CONTACT 테이블

CONTACT(ContactName, Phone)

역할:

  • ContactName이 결정자
  • 담당자 이름이 여러 고객 레코드에서 반복되더라도 Phone 중복 없이 관리 가능

정규화의 부작용: 구조 복잡성 증가

정규화는 테이블을 여러 개로 나누기 때문에

데이터 구조가 지나치게 복잡해질 수 있다.


비정규화 후 테이블

CUSTOMER 테이블 (비정규화 버전)

CUSTOMER(CustomerNumber, CustomerName, StreetAddress,
         City, State, ZIP, ContactName)

특징

  • City, State를 ZIP으로부터 분리하지 않음
  • ZIP 테이블을 따로 두지 않아도 됨
  • 조회 시 JOIN 필요 없음

CONTACT 테이블

CONTACT(ContactName, Phone)

특징

  • 담당자(ContactName)와 전화번호는 분리하여 관리
  • ContactName이 반복될 가능성이 낮거나,

    Phone 정보가 여러 고객에 공유될 수 있는 경우 유용


Representing Weak Entities

Weak Entity(약한 엔티티)는 자체적으로 고유하게 식별될 수 없기 때문에 관계형 모델로 변환할 때 부모 엔티티(Owner) 의 Primary Key 사용 여부에 따라 두 가지 방식으로 나뉜다.

1) Weak Entity가 ID-dependent가 아닌 경우

Weak Entity가 ID-dependent가 아닌 경우란?

  • 약한 엔티티이지만 자신의 속성만으로 기본 키를 구성할 수 있는 경우
  • 또는 식별 관계(identifying relationship)가 아닌 경우

→ 이 경우 Strong Entity(강한 엔티티)와 동일한 방식으로 테이블 생성

즉:

  • 자체 Primary Key 지정
  • 필요한 속성 정의
  • 필요 시 Foreign Key만 추가

강한 엔티티와 크게 다르지 않다.

2) Weak Entity가 ID-dependent인 경우

ID-dependent란?

  • 약한 엔티티의 존재가 부모 엔티티의 식별자(PK)에 완전히 의존하는 경우
  • 부모 엔티티의 Primary Key가 없으면 자식 엔티티의 행을 식별할 수 없음

→ 반드시 부모 엔티티의 PK를 포함해야 함

이때 약한 엔티티의 Primary Key 구성:

  • 부모 엔티티의 PK + 자신의 Partial Key 조합
  • 이를 통해 유일성 확보

Representing Relationships

관계 표현의 기준 = 최대 카디널리티(Maximum Cardinality)

관계(relationship)를 테이블로 표현할 때,

가장 중요한 기준은 최대 카디널리티이다.

1:1, 1:N, N:M의 형태에 따라

  • Foreign Key(FK) 위치
  • 별도 테이블 생성 여부
  • 식별 관계인지 여부

    등이 결정된다.

1:1 관계 표현 방식

→ 한 테이블의 Primary Key를 다른 테이블에 Foreign Key로 넣어 표현한다.

  • 두 테이블 중 어느 쪽에 FK를 넣어도 괜찮음
  • 즉, FK의 위치는 중요하지 않음

이유:

  • 최대 1개만 연결되므로 방향성이 의미가 없음
  • 데이터 중복이 발생하지 않음
  • JOIN 구조도 동일한 의미 유지 가능

1:N 관계 표현 방식

→ 1:1 관계와 동일하게 Foreign Key로 표현하지만, 위치가 다르다.

중요 규칙: Foreign Key는 항상 N(다수) 쪽에 배치한다.

  • 1 쪽(부모, Parent)은 FK를 갖지 않는다
  • N 쪽(자식, Child)이 부모의 Primary Key를 FK로 포함한다

이유

1:N 관계에서는

  • 1 쪽의 한 행이 여러 행과 연결될 수 있음
  • 따라서 다수(N) 쪽이 부모의 PK를 저장해야 정확한 매핑이 가능함
  • 반대로 1 쪽에 FK를 둔다면 여러 값을 저장해야 하므로 불가능

N:M 관계 표현 방식

→ 반드시 새로운 테이블을 생성해야 한다.

이 새로운 테이블을 교차 테이블(Intersection Table) 또는 연결 테이블(Linking Table) 이라고 한다.

Intersection Table의 구성

두 테이블의 Primary Key를 모두 포함한다

  • Parent/Child 개념이 아니라

    → 두 엔티티의 PK가 모두 필요

  • Intersection Table의 Primary Key는 복합 Primary Key(Composite Key) 로 구성된다.

왜 테이블을 따로 만들까?

  • 한 학생이 여러 강의를
  • 한 강의가 여러 학생을 수강할 수 있으므로

    → 하나의 FK만으로는 관계 표현이 불가능

따라서 두 테이블의 연결 정보만 저장하는 독립된 테이블이 필요하다.

Lec-06-2

Storage (저장 구조)

DBMS가 데이터를 저장·관리하는 과정은 크게 다음 계층으로 나눌 수 있다.

  • File Systems (파일 시스템)

    운영체제가 제공하는 기본 저장 구조로, 파일 단위로 데이터를 저장한다.

  • Direct Device Management

    DBMS가 OS 파일 시스템을 사용하지 않고 디스크 장치를 직접 관리하는 방식.

    성능 최적화를 위해 DBMS가 자체적으로 블록/페이지 단위로 데이터를 배치한다.

Key Issues

I/O 최소화

디스크 접근은 매우 느리므로, 데이터를 효율적으로 배치해 접근 횟수를 줄여야 한다.

Access Pattern 최적화

Row-store(행 저장) / Column-store(열 저장) 선택에 따라 성능이 큰 차이를 보인다.

Hash-based Indexes

Static Hashing

  • 버킷 수 고정
  • 해시값 mod N
  • 데이터가 증가하면 버킷 overflow → 성능 저하

Extensible Hashing

  • 디렉토리 + 버킷 구조
  • 필요할 때만 버킷을 분할 (directory doubling)
  • 데이터 증가에 더 유연하게 대처

Buffer Management (버퍼 관리)

DBMS는 페이지를 Buffer Pool에 적재하여 캐싱한다.

Why buffer management matters

  • 디스크 I/O 회수를 감소
  • 자주 사용하는 페이지를 메모리에 유지

DBMS vs File System Buffer Cache

  • OS의 파일 캐시와 목적이 다름
  • DBMS는 페이지 단위, 트랜잭션, 로그·회복 시스템을 고려해야 함
  • 따라서 대부분 DBMS는 자체 버퍼 관리 시스템을 유지함

Lec-06-3-RAID

Lec-07-1

Lec-08-1 Mysql

기말 연습 문제

ITE316-final-sample

Question.

  1. Briefly explain the distinction between the RAID0, RAID1, and RAID5 disk organizations.

RAID 0 stripes data across multiple disks to increase performance but provides no redundancy, RAID 1 mirrors data across disks to provide full redundancy, and RAID 5 stripes data with distributed parity to offer both improved performance and fault tolerance with efficient storage use.
  1. Explain the difference between an explicit lock and an implicit lock.

An explicit lock is one that a transaction requests directly using lock commands, while an implicit lock is automatically applied by the database system when certain operations occur.
  1. Distinguish between an entity class and an entity instance.

An entity class describes the common structure and attributes of a group of similar entities, while an entity instance is a single specific occurrence of that entity class.

Question.

  1. The following database will be used in this question :

    Write the SQL statement to create a view named CustmerSalesRepView that displays the customer name as CustomerName and the associated sales rep name as SaleRepresentativeName from the GENERAL SALES DATABASE.

    sql
    CREATE VIEW CustmerSalesRepView AS
    SELECT 
        CUSTOMER.CustName AS CustomerName,
        SALESREP.RepName AS SaleRepresentativeName
    FROM CUSTOMER
    JOIN SALESREP
        ON CUSTOMER.SalesRepNo = SALESREP.SalesRepNo;
  1. Write the schema to represent the entities below, including tables, the proper placement of the foreign key, and referential integrity constraint.

    sql
    CREATE TABLE ADVISOR (
        AdvisorID   INT         PRIMARY KEY,
        AdvName     VARCHAR(50),
        AdvOffice   VARCHAR(50),
        AdvPhone    VARCHAR(20)
    );
    
    CREATE TABLE STUDENT (
        StudentID   INT         PRIMARY KEY,
        StuName     VARCHAR(50),
        StuMajor    VARCHAR(50),
        StuPhone    VARCHAR(20),
        AdvisorID   INT,
        
        FOREIGN KEY (AdvisorID)
            REFERENCES ADVISOR(AdvisorID)
    );

    Question.

    1. For the following database schema :

      where

      Assume that OwnerID in OWNER, PropertyID in PROPERTY, and EmployeeID in EMPLOYEE are surrogate keys with values as follows :

      Draw an E-R data model. Use the IE Crow’s Foot E-R model for your E-R diagrams. Explain your decisions regarding minimum and maximum cardinality.

추가 문제 (제작)

~5. SQL, E-R Model

E-R Model

  1. What condition makes an entity ID-dependent?

    An entity is ID-dependent if its identifier includes the identifier of its parent strong entity as part of its own composite primary key.
  2. What is the difference between an ID-dependent weak entity and a non-ID-dependent weak entity?

    • An ID-dependent weak entity has a composite identifier that includes the parent’s identifier.
    • A non-ID-dependent weak entity has its own identifier, but still depends on a parent entity; the parent’s identifier appears only as a foreign key, not part of the primary key.
  3. Can a weak entity have its own attributes? If yes, explain.

    Yes. A weak entity may have its own attributes, but it cannot be uniquely identified without the parent entity’s identifier.

SQL

  1. The following database will be used in this question.

    LIBRARY LOAN DATABASE

    BOOK

    BookIDTitleGenreAuthorID
    210NightfallSci-Fi501
    330The Long RoadDrama502
    120Last KingdomFantasy503
    410Beyond the StarsSci-Fi501

    AUTHOR

    AuthorIDAuthorNameBirthYear
    501Asimov1920
    502Carter1975
    503Hill1981

    Write the SQL statement to create a view named BookAuthorView that displays :

    • the book title as BookTitle, and
    • the corresponding author name as WriterName

    from the LIBRARY LOAN DATABASE.

    sql
    CREATE VIEW BookAuthorView AS
    SELECT 
        BOOK.Title AS BookTitle,
        AUTHOR.AuthorName AS WriterName
    FROM BOOK
    JOIN AUTHOR
        ON BOOK.AuthorID = AUTHOR.AuthorID;
  2. The following database will be used in this question.

    UNIVERSITY COURSE ANALYTICS DATABASE

    STUDENT

    StudentIDFirstNameLastNameMajorGradYear
    2001AliceParkCS2025
    2002BrianKimEE2024
    2003CindyLeeCS2026

    COURSE

    CourseIDCourseNameCredits
    501Database Systems3
    502Algorithms3
    503Operating Systems4

    ENROLLMENT

    StudentIDCourseIDGradeSemester
    200150192Fall2024
    200150285Fall2024
    200250178Fall2024
    200350388Spring2025
    200350191Spring2025

    Write the SQL statement to create a view named StudentCoursePerformanceView that displays :

    • full student name as FullName (FirstName + space + LastName) (Hint : use “CONCAT”)
    • the course name as CourseName
    • the number of credits for that course as CourseCredits
    • the student’s grade as Grade
    • a calculated column GradeLevel:
      • ‘High’ if Grade >= 90
      • ‘Medium’ if Grade BETWEEN 80 AND 89
      • ‘Low’ otherwise
    • but only include rows for CS majors
    • and only include enrollments from 2024 or later

    sql
    CREATE VIEW StudentCoursePerformanceView AS
    SELECT 
        CONCAT(S.FirstName, ' ', S.LastName) AS FullName,
        C.CourseName AS CourseName,
        C.Credits AS CourseCredits,
        E.Grade AS Grade,
        CASE 
            WHEN E.Grade >= 90 THEN 'High'
            WHEN E.Grade BETWEEN 80 AND 89 THEN 'Medium'
            ELSE 'Low'
        END AS GradeLevel
    FROM STUDENT S
    JOIN ENROLLMENT E
        ON S.StudentID = E.StudentID
    JOIN COURSE C
        ON E.CourseID = C.CourseID
    WHERE S.Major = 'CS'
      AND (
            E.Semester LIKE 'Fall2024%' 
            OR E.Semester LIKE 'Spring2025%' 
            OR RIGHT(E.Semester, 4) >= '2024'
          );
  3. Using INSTRUCTOR, TEACHES, and COURSE, write a SQL query that returns the name of each instructor who has taught at least one course in every department that they have ever taught in.

    In other words, for each instructor, check whether there exists any department in which the instructor has taught zero courses. Use a NOT EXISTS pattern with nested subqueries, similar to the "students who have taken every Biology course" pattern.

    tablescolumns
    INSTRUCTORID, name, dept_name
    COURSEcourse_id, title, dept_name
    TEACHESID, course_id, sec_id, semester, year

    Write the standard SQL query.

    정답 및 해설

    sql
    SELECT i.name
    FROM INSTRUCTOR i
    WHERE NOT EXISTS (
        SELECT DISTINCT c.dept_name
        FROM COURSE c
        JOIN TEACHES t ON c.course_id = t.course_id
        WHERE t.ID = i.ID
          AND c.dept_name NOT IN (
                SELECT c2.dept_name
                FROM COURSE c2
                JOIN TEACHES t2 ON c2.course_id = t2.course_id
                WHERE t2.ID = i.ID
            )
    );
    

    INSTRUCTOR, TEACHES, COURSE 세 테이블을 이용해

    각 교수(instructor)가 자신이 가르친 모든 학과(dept_name)에서 최소 한 과목 이상 가르쳤는지 검사하는 문제이다.

    즉, 교수 A가

    • CS 과목도 가르쳤고
    • Math 과목도 가르쳤다면

    이 교수는 CS에서도 최소 1과목, Math에서도 최소 1과목을 가르쳐야 한다.

    어떤 학과(dept_name)에서라도

    “이 교수는 이 학과에서는 아무 과목도 안 가르쳤다”

    라는 상황이 있으면 불합격,

    그런 학과가 하나도 없으면 결과에 포함된다.

    Step

    1. 먼저 교수 i가 가르친 학과 목록을 찾는다.

    sql
    SELECT DISTINCT c.dept_name
    FROM COURSE c
    JOIN TEACHES t ON c.course_id = t.course_id
    WHERE t.ID = i.ID

    2. 그 중에서 교수 i가 해당 학과에서 과목을 하나도 가르치지 않은 학과를 찾는다.

    sql
    AND c.dept_name NOT IN (
        SELECT c2.dept_name
        FROM COURSE c2
        JOIN TEACHES t2 ON c2.course_id = t2.course_id
        WHERE t2.ID = i.ID
    )

    3. 최종적으로, 교수가 가르친 학과 중 조건을 만족하지 못하는 학과가 ‘존재하지 않아야’ 한다.

    그렇기에 전체를 감싸는 것이 바로 :

    sql
    WHERE NOT EXISTS ( ... )

    이다.

  1. Using EMPLOYEE, PROJECT, and WORKS_ON, write a SQL query that returns the name of each employee who has worked on all projects in their department.

    In other words, for each employee, check whether the count of projects they worked on in their department matches the total number of projects in that department. Use GROUP BY and HAVING.

    Write the standard SQL query.

    tablescolumns
    EMPLOYEEeid, name, dept_name
    PROJECTpid, pname, dept_name
    WORKS_ONeid, pid, hours

    정답 및 해설

    sql
    SELECT e.name
    FROM EMPLOYEE e
    JOIN WORKS_ON w ON e.eid = w.eid
    JOIN PROJECT p ON w.pid = p.pid
    WHERE e.dept_name = p.dept_name
    GROUP BY e.eid, e.name
    HAVING COUNT(DISTINCT p.pid) = (
        SELECT COUNT(*)
        FROM PROJECT p2
        WHERE p2.dept_name = e.dept_name
    );

    EMPLOYEE, WORKS_ON, PROJECT 세 테이블을 이용해

    각 직원(employee)이 자신이 속한 부서(dept_name)의 모든 프로젝트에서 최소 한 번 이상 참여했는지 검사하는 문제이다.

    즉, 직원 A가

    • 부서 내 프로젝트 P1, P2, P3가 있고
    • A가 P1, P2, P3 모두 참여했으면

    이 직원은 결과에 포함된다.

    부서 내 프로젝트 중 하나라도 참여하지 않은 프로젝트가 있으면 결과에 포함되지 않는다.

    Step

    1. 먼저 직원 e가 참여한 부서 내 프로젝트 목록을 확인한다.
    sql
    SELECT p.pid
    FROM PROJECT p
    JOIN WORKS_ON w ON p.pid = w.pid
    WHERE w.eid = e.eid AND p.dept_name = e.dept_name;
    1. 부서 내 총 프로젝트 수를 구한다.
    sql
    SELECT COUNT(*)
    FROM PROJECT p2
    WHERE p2.dept_name = e.dept_name;
    1. 최종적으로 직원이 참여한 프로젝트 수와 부서 내 총 프로젝트 수가 같으면 결과에 포함시킨다.

    그렇기에 전체 쿼리는 GROUP BYHAVING을 사용하여 직원별로 조건을 체크한다.

6-1. Design

  1. The following tables describe a database for a university course scheduling system. Using the information below, draw a complete E-R data model using Crow’s Foot notation. Include all entities, attributes, primary keys, foreign keys, and relationship cardinalities.
    json
    INSTRUCTOR (InstructorID, LastName, FirstName, Email)
    COURSE (CourseID, CourseTitle, Credits, Department)
    SECTION (SectionID, CourseID, InstructorID, Semester, Year)
    ENROLLMENT (SectionID, StudentID, EnrollDate)
    STUDENT (StudentID, LastName, FirstName, Major, Status)
    
    CourseID in SECTION must exist in COURSE.
    InstructorID in SECTION must exist in INSTRUCTOR.
    SectionID in ENROLLMENT must exist in SECTION.
    StudentID in ENROLLMENT must exist in STUDENT.
    
    InstructorID starts at 1 and increments by 1.
    CourseID starts at 1 and increments by 1.
    SectionID starts at 1 and increments by 1.
    StudentID starts at 1 and increments by 1.

    Draw an E-R data model. Use the IE Crow’s Foot E-R model for your E-R diagrams. Explain your decisions regarding minimum and maximum cardinality.

    정답 및 해설

    1. COURSE — SECTION

    • COURSE (1) ——< SECTION (N)

      이유: 한 과목은 여러 개의 섹션을 가질 수 있지만, 한 섹션은 반드시 하나의 과목에 속함.


    2. INSTRUCTOR — SECTION

    • INSTRUCTOR (1) ——< SECTION (N)

      이유: 한 강사는 여러 섹션을 맡을 수 있음.

      SECTION.InstructorID는 NULL이 아니므로 최소 참여 = 1.


    3. SECTION — STUDENT (ENROLLMENT을 통한 N:M)

    • SECTION (N) ——< ENROLLMENT >—— (N) STUDENT

      이유:

    • 한 학생은 여러 섹션을 들을 수 있고
    • 한 섹션도 여러 학생을 포함할 수 있음

      → 전형적인 N:M 관계라서 ENROLLMENT라는 교차 테이블 필요.

    mermaid
    erDiagram
    
        INSTRUCTOR {
            int InstructorID PK
            string LastName
            string FirstName
            string Email
        }
    
        COURSE {
            int CourseID PK
            string CourseTitle
            int Credits
            string Department
        }
    
        SECTION {
            int SectionID PK
            int CourseID FK
            int InstructorID FK
            string Semester
            int Year
        }
    
        STUDENT {
            int StudentID PK
            string LastName
            string FirstName
            string Major
            string Status
        }
    
        ENROLLMENT {
            int SectionID PK,FK
            int StudentID PK,FK
            date EnrollDate
        }
    
        %% Relationships
        COURSE ||--o{ SECTION : "offers"
        INSTRUCTOR ||--o{ SECTION : "teaches"
        SECTION ||--o{ ENROLLMENT : "has"
        STUDENT ||--o{ ENROLLMENT : "takes"
    

  1. The following tables describe a database for a real-estate management system. Using the information below, draw a complete E-R data model using Crow’s Foot notation. Include all entities, attributes, primary keys, foreign keys, and relationship cardinalities.
    json
    RESEARCHER (ResearcherID, LastName, FirstName, Email, Rank)
    LAB (LabID, LabName, Building, Floor, SupervisorID)
    PROJECT (ProjectID, ProjectTitle, StartDate, EndDate, LabID)
    ASSIGNMENT (ProjectID, ResearcherID, AssignedDate, Role)
    FUNDING (FundingID, ProjectID, SourceName, Amount, AwardDate)
    
    SupervisorID in LAB must exist in ResearcherID in RESEARCHER.
    LabID in PROJECT must exist in LabID in LAB.
    ProjectID in ASSIGNMENT must exist in ProjectID in PROJECT.
    ResearcherID in ASSIGNMENT must exist in ResearcherID in RESEARCHER.
    ProjectID in FUNDING must exist in ProjectID in PROJECT.
    
    ReasearcherID Start at 1 Increment by 1
    LabID Start at 1 Increment by 1
    ProjectID Start at 1 Increment by 1
    FundingID Start at 1 Increment by 1

    Draw an E-R data model. Use the IE Crow’s Foot E-R model for your E-R diagrams. Explain your decisions regarding minimum and maximum cardinality.

    정답 및 해설

    1. RESEARCHER — LAB

    • RESEARCHER (1) ——< LAB (N)

      이유: 한 연구자는 여러 실험실을 감독할 수 있고, LAB은 반드시 하나의 Supervisor를 가져야 함.


    2. LAB — PROJECT

    • LAB (1) ——< PROJECT (N)

      이유: 한 실험실에 여러 프로젝트가 있을 수 있고, 각 프로젝트는 반드시 하나의 실험실에 속함.


    3. PROJECT — RESEARCHER (ASSIGNMENT 통해 N:M)

    • PROJECT (N) ——< ASSIGNMENT >—— (N) RESEARCHER

      이유: 연구자는 여러 프로젝트에 참여할 수 있고, 프로젝트도 여러 연구자를 가질 수 있음.


    4. PROJECT — FUNDING

    • PROJECT (1) ——< FUNDING (N)

      이유: 한 프로젝트는 여러 Funding을 받을 수 있고, Funding은 반드시 한 프로젝트에 속함.

    mermaid
    erDiagram
    
        RESEARCHER {
            int ResearcherID PK
            string LastName
            string FirstName
            string Email
            string Rank
        }
    
        LAB {
            int LabID PK
            string LabName
            string Building
            int Floor
            int SupervisorID FK
        }
    
        PROJECT {
            int ProjectID PK
            string ProjectTitle
            date StartDate
            date EndDate
            int LabID FK
        }
    
        ASSIGNMENT {
            int ProjectID PK,FK
            int ResearcherID PK,FK
            date AssignedDate
            string Role
        }
    
        FUNDING {
            int FundingID PK
            int ProjectID FK
            string SourceName
            float Amount
            date AwardDate
        }
    
        %% Relationships
    
        RESEARCHER ||--o{ LAB : "supervises"
        LAB ||--o{ PROJECT : "has"
        PROJECT ||--o{ FUNDING : "receives"
        PROJECT ||--o{ ASSIGNMENT : "related to"
        RESEARCHER ||--o{ ASSIGNMENT : "participates in"
    
    

6-2. Hashing

  1. The hash table shown below contains 4 buckets (0–3). Each bucket can store up to 3 records.

    The hash function is:

    Insert the following records into the hash table in the given order:

    12 Carter 33 Nolan 47 Price 25 Grant 52 Adams 19 Baker 44 Young 31 Olsen

    Instructions

    • Compute h(x) for each key.
    • Insert the record into the corresponding bucket.
    • If collisions occur, place the record in the next available slot inside the same bucket.
    • If a bucket becomes full, mark additional insertions as overflow (no further handling required).
    Answer format
    agda
    Bucket 0:
    Bucket 1:
    Bucket 2:
    Bucket 3:

    정답 및 해설

    1. 12 Carter

    12 mod 4 = 0 → Bucket 0

    2. 33 Nolan

    33 mod 4 = 1 → Bucket 1

    3. 47 Price

    47 mod 4 = 3 → Bucket 3

    4. 25 Grant

    25 mod 4 = 1 → Bucket 1

    5. 52 Adams

    52 mod 4 = 0 → Bucket 0

    6. 19 Baker

    19 mod 4 = 3 → Bucket 3

    7. 44 Young

    44 mod 4 = 0 → Bucket 0

    8. 31 Olsen

    31 mod 4 = 3 → Bucket 3

    agda
    Bucket 0:
    12  Carter
    52  Adams
    44  Young
    
    Bucket 1:
    33  Nolan
    25  Grant
    
    Bucket 2:
    (empty)
    
    Bucket 3:
    47  Price
    19  Baker
    31  Olsen

7-1. Admin

  1. Which of the following best describes a dirty read?

    A. A transaction reads a value that has already been rolled back

    B. A transaction reads a value that another transaction has written but not committed

    C. A transaction overwrites another transaction’s committed data

    D. A transaction reads only committed data but in the wrong orde

    B

  2. In strict two-phase locking (Strict 2PL), when are all exclusive locks released?

    A. Immediately after writing

    B. When the growing phase ends

    C. Only after the transaction commits

    D. Only when another transaction requests the same item

    C

  3. Which of the following scenarios can lead to a lost update?

    A. Two transactions both commit after reading each other’s updates

    B. Two transactions update the same item simultaneously and one update overwrites the other

    C. A transaction reads uncommitted data

    D. A transaction is forced to rollback due to deadlock

    B

  4. 5. Which locking mode allows multiple transactions to read the same item but prevents updates?

    A. Exclusive lock (X-lock)

    B. Shared lock (S-lock)

    C. Intent exclusive lock

    D. Update lock

    B

  5. What is a characteristic of optimistic locking?

    A. Locks are acquired before reading

    B. Conflicts are checked only at commit time

    C. All operations require an explicit lock

    D. Reads are blocked whenever another transaction holds a lock

    B

  6. Four users (A, B, C, and D) are concurrently accessing a database. Each user performs a transaction on a specific item, following these steps:
    sql
    1. Lock the item.
    2. Read the item.
    3. Modify the item’s value.
    4. Write the item.
    5. Release the lock.

    Their individual actions are:

    sql
    User A
    	Lock Item 200
    	Read Item 200
    	Increase value by 10
    	Write Item 200
    	Unlock Item 200
    
    User B
    	Lock Item 200
    	Read Item 200
    	Decrease value by 4
    	Write Item 200
    	Unlock Item 200
    
    User C
    	Lock Item 350
    	Read Item 350
    	Multiply value by 2
    	Write Item 350
    	Unlock Item 350
    
    User D
    	Lock Item 200
    	Read Item 200
    	Increase value by 7
    	Write Item 200
    	Unlock Item 200

    Assume the database server uses strict two-phase locking (strict 2PL).

    Item 200 is shared among Users A, B, and D, while Item 350 is only accessed by User C.

    Construct a possible valid order of processing at the database server, showing:

    • When each user successfully locks an item
    • When a user must wait
    • When another user’s lock is released
    • When their read/modify/write operations occur

    Your answer should list the transitions in order, similar to the example shown in the diagram.

    정답 및 해설

    전제

    • A, B, D는 모두 Item 200을 사용하므로 서로 Lock 경쟁이 일어난다.
    • C는 Item 350만 사용하므로 독립적으로 수행할 수 있으며 다른 사용자와 경합이 없다.
    • Strict 2PL에서는 트랜잭션이 완료될 때까지 Lock을 해제하지 않는다.

    1. User A가 먼저 시작한다고 가정

    1. Item 200에 대해 A가 Lock 획득
    2. A가 Item 200 읽기
    3. A가 값에 +10 적용
    4. A가 Item 200 쓰기
    5. A가 트랜잭션 종료하면서 Lock 해제

    → 이 동안 B와 D는 Item 200 Lock 요청 → 대기 상태가 된다.


    2. User C는 Item 350을 사용하므로 독립적으로 처리 가능

    (순서 어디에 위치해도 충돌 없음)

    1. C가 Item 350 Lock 획득
    2. C가 Item 350 읽기
    3. C가 값 × 2 적용
    4. C가 Item 350 쓰기
    5. C가 Lock 해제

    3. A가 끝났으므로 Item 200 Lock을 기다리던 B가 다음으로 처리됨

    1. B가 Item 200 Lock 획득
    2. B가 Item 200 읽기
    3. B가 값 -4 적용
    4. B가 Item 200 쓰기
    5. B가 Lock 해제

    → D는 계속 대기 중이었는데, 이제 B의 Lock 해제로 진행할 수 있다.


    4. 마지막으로 User D 처리

    1. D가 Item 200 Lock 획득
    2. D가 Item 200 읽기
    3. D가 값 +7 적용
    4. D가 Item 200 쓰기
    5. D가 Lock 해제

    정리된 최종 서버 처리 순서

    아래는 전체 흐름을 일련의 transition으로 정렬한 예시이다.

    1. Lock Item 200 for A
    2. Read Item 200 for A
    3. Modify (+10)
    4. Write Item 200 for A
    5. Unlock Item 200 for A
    6. Lock Item 350 for C
    7. Read Item 350 for C
    8. Modify (×2)
    9. Write Item 350 for C
    10. Unlock Item 350 for C
    11. Lock Item 200 for B
    12. Read Item 200 for B
    13. Modify (–4)
    14. Write Item 200 for B
    15. Unlock Item 200 for B
    16. Lock Item 200 for D
    17. Read Item 200 for D
    18. Modify (+7)
    19. Write Item 200 for D
    20. Unlock Item 200 for D
  7. A database maintains two shared items: Item A and Item B. Four users (T1, T2, T3, T4) execute the following transactions concurrently.

    Transactions

    T1

    1. Lock A (X)
    2. Read A
    3. A = A + 10
    4. Lock B (X)
    5. Read B
    6. B = B × 2
    7. Write B
    8. Write A
    9. Unlock A, Unlock B

    T2

    1. Lock B (X)
    2. Read B
    3. B = B − 5
    4. Write B
    5. Lock A (X)
    6. Read A
    7. A = A + 1
    8. Write A
    9. Unlock A, Unlock B

    T3

    1. Read A (No lock → Optimistic)
    2. Compute A × 3
    3. At commit time, check conflicts
    4. If no conflict → Write A
    5. Else → Rollback and retry

    T4

    1. Lock A (S)
    2. Read A
    3. Unlock A
    • Strict 2PL applies to T1 and T2 only.
    • T3 uses Optimistic Locking (from the lecture).
    • T4 uses Shared Lock (S-lock).
    • X-lock and S-lock are incompatible.
    • If conflict exists, T3 must abort and restart.
    • Initial values: A = 50, B = 20

    2-1. Show a possible execution order that results in a deadlock between T1 and T2, based on their lock requests.

    (1) Deadlock Sequence (T1 vs T2)

    1. T1: Lock A(X) → success
    2. T2: Lock B(X) → success
    3. T1: requests Lock B(X) → waits (T2 owns B)
    4. T2: requests Lock A(X) → waits (T1 owns A)

    → Both transactions wait on each other

    Deadlock occurred

    2-2. After the deadlock, assume the DBMS chooses T2 as the victim and rolls it back. Continue the schedule with T1 completing normally. Provide the full sequence of transitions:

    • which transaction obtains which lock
    • who waits
    • deadlock detection
    • victim selection
    • rollback
    • remaining operations executed

    (2) Deadlock resolution & full schedule

    Deadlock detector selects T2 as victim.

    Rollback T2

    • Undo change to B
    • Release Lock B

    Now T1 continues:

    1. T1: acquires Lock B(X)
    2. Read B (20)
    3. B = 40
    4. Write B
    5. Read A (50)
    6. A = 60
    7. Write A
    8. Unlock A, Unlock B

      T1 completes successfully

    2-3. Now consider T3 running concurrently during this schedule.

    Show a timeline where:

    • T3 reads A = 50
    • But before commit, T1 modifies A
    • Therefore T3 must detect conflict and rollback

    Give the timeline of T3’s events.

    (3) T3 conflict timeline

    T3 uses Optimistic Locking:

    1. T3 reads A = 50 (No lock)
    2. Computes A × 3 = 150
    3. T1 modifies A to 60
    4. T3 validation phase:
      • Checks whether A changed during T3’s transaction
      • A changed from 50 → 60
    5. Conflict detected → T3 must rollback
    6. T3 restarts later

    2-4. Finally, show where T4 can safely run with its shared lock without violating strict 2PL, and explain why it does not cause a dirty read.

    (4) T4 shared-lock safe window

    T4 performs:

    1. Lock A (S)
    2. Read A
    3. Unlock A

    T4 can run after T1 commits, because:

    • Strict 2PL: T1 keeps X-lock on A until commit
    • After commit: X-lock released
    • T4’s S-lock does not conflict with any uncommitted write

    Therefore:

    • T4 does NOT read uncommitted data
    • No dirty read occurs

8-1. Mysql

  1. In mysql, If you are not satisfied with one or more of the changes and you want to revert those changes completely, what method should you use?

    sql
    db.rollback()

  1. In mysql, To disconnect Database connection, what method should you use?

    sql
    db.close()

기말 족보

View SQL 문 작성문제 중간보다 많아짐(2문제?, 연습 문제와 비슷함)

Join SQL 작성 (2문제?)

Relational Algebra

RAID0, RAID1, RAID5의 차이를 설명하라. → 연습문제 그대로

Stack hashing 직접 해보는 문제

Crow Foot 사용해서 DB 구조 그리기

Concurrent Processing 4명짜리 순서 정하기

파이썬 mysql Operation 물어봤음

Seoul, South Korea

jwsong5160@gmail.com

© 2026 Junwoo Song