Skip to content · ⁨본문 바로가기⁩
Subjects · ⁨과목⁩
  • 1 Querying basics · ⁨쿼리 기초⁩
    1.1

    SELECT 및 FROM

    English

    A database 数据库 keeps data in tables 表. A query 查询 reads data with SELECT. SELECT * returns every column; FROM names the table.

    • Each row 行 is one record 记录. SQL keywords are written in UPPERCASE by habit.
    • A statement ends with a semicolon ;.
    한국어

    데이터베이스는 테이블에 데이터를 유지합니다. 쿼리는 SELECT를 사용하여 데이터를 읽습니다. SELECT *는 모든 열을 반환하며; FROM는 테이블 이름을指定합니다.

    CREATE TABLE student (id INTEGER, name TEXT, score INTEGER);
    INSERT INTO student VALUES (1, 'Mei', 88), (2, 'Sam', 71);
    SELECT * FROM student;
    
    테이블은 레코드를 저장함: 각 행은 하나의 레코드이며, 각 열은 하나의 필드임
    테이블은 레코드를 저장함: 각 행은 하나의 레코드이며, 각 열은 하나의 필드임
    • 각 행은 하나의 레코드입니다. SQL 키워드는 관례에 따라 대문자로 표기됩니다.
    • 명령어는 세미콜론 ;로 끝납니다.
    1.2

    열 선택하기

    English

    List the columns 列 you want, separated by commas. Use AS to rename a column in the result (an alias 别名).

    A selected column can also be a calculation — pair it with AS to name the new column:

    • SELECT DISTINCT col removes duplicate values from the result.
    한국어

    원하는 열을 나열하고, 콤마(,)로 구분하십시오. 결과에서 열 이름을 바꾸려면 AS를 사용하십시오(별명).

    CREATE TABLE student (id INTEGER, name TEXT, score INTEGER);
    INSERT INTO student VALUES (1, 'Mei', 88), (2, 'Sam', 71);
    SELECT name, score AS mark FROM student;
    

    선택된 열은 계산식일 수도 있습니다 — 새로운 열 이름으로 지정하려면 AS와 함께 사용하십시오:

    CREATE TABLE student (id INTEGER, name TEXT, score INTEGER);
    INSERT INTO student VALUES (1, 'Mei', 88), (2, 'Sam', 71);
    SELECT name, score + 5 AS bonus FROM student;
    
    • SELECT DISTINCT col는 결과에서 중복 값을 제거합니다.
    1.3

    WHERE로 필터링하기

    English

    WHERE keeps only the rows that match a condition 条件. Compare with =, <> (not equal), <, >, <=, >=. Put text in single quotes.

    • SQL runs the parts in this order: FROM → WHERE → SELECT.

    Common mistakes

    • Put text values in single quotes: WHERE name = 'Ann'; column names have no quotes.
    • SELECT * returns every column — name only the columns you need.
    • WHERE filters rows; it comes after FROM.
    한국어

    WHERE는 조건에 일치하는 행만 유지합니다. =, <>(불일치), <, >, <=, >=와 비교하십시오. 텍스트는 단일 따옴표로 묶으십시오.

    CREATE TABLE student (id INTEGER, name TEXT, score INTEGER);
    INSERT INTO student VALUES (1, 'Mei', 88), (2, 'Sam', 71), (3, 'Ana', 95);
    SELECT name, score FROM student WHERE score >= 80;
    
    • SQL은 다음과 같은 순서로 부분을 실행합니다: FROM → WHERE → SELECT.

    Common mistakes

    • 텍스트 값은 단일 따옴표로 묶으십시오: WHERE name = 'Ann'; 열 이름에는 따옴표를 사용하지 않습니다.
    • SELECT *는 모든 열을 반환하므로 — 필요한 열만 명시하십시오.
    • WHERE는 행을 필터링하며; FROM 뒤에 위치합니다.
  • 2 Filtering & logic · ⁨필터링 및 논리⁩
    2.1

    AND, OR, NOT

    English

    Combine conditions with AND, OR, NOT. AND needs all sides true; OR needs any side true; NOT reverses one. Use brackets to set the precedence 优先级.

    한국어

    AND, OR, NOT로 조건을 결합하십시오. AND는 모든 부분이 참이어야 하고; OR는 어느 쪽이 참이면 되고; NOT는 하나를 반전시킵니다. 우선순위를 설정하려면 괄호를 사용하십시오.

    CREATE TABLE student (id INTEGER, name TEXT, form TEXT, score INTEGER);
    INSERT INTO student VALUES (1,'Mei','11A',88),(2,'Sam','11B',71),(3,'Ana','11A',95);
    SELECT name FROM student WHERE form = '11A' AND score >= 90;
    
    AND는 모두 참이어야 함; OR는任一 참이어야 함; NOT는 하나 반전
    AND는 모두 참이어야 함; OR는任一 참이어야 함; NOT는 하나 반전
    2.2

    LIKE, IN 및 BETWEEN

    English

    LIKE matches a text pattern 模式: % stands for any text and _ for one character — these are wildcards 通配符.

    Pattern Matches
    'M%' starts with M
    '%a' ends with a
    '%an%' contains "an"
    'M_i' M, then exactly one character, then i

    IN matches a set 集合 of values; BETWEEN matches a range 范围 (both ends included).

    한국어

    LIKE는 텍스트 패턴과 일치합니다: %는 임의의 텍스트를 나타내고 _는 하나의 문자를 나타내며 — 이들은Registrar(wildcard)입니다.

    CREATE TABLE student (id INTEGER, name TEXT, form TEXT, score INTEGER);
    INSERT INTO student VALUES (1,'Mei','11A',88),(2,'Sam','11B',71),(3,'Ana','11A',95);
    SELECT name FROM student WHERE name LIKE 'M%';        -- starts with M
    
    패턴 일치함
    'M%' M로 시작함
    '%a' a로 끝남
    '%an%' "an" 포함
    'M_i' M, 그 다음 정확히 하나의 문자, 그리고 i

    IN는 값의 집합과 일치하며; BETWEEN은 범위를 일치시킵니다(양쪽 끝 포함).

    CREATE TABLE student (id INTEGER, name TEXT, form TEXT, score INTEGER);
    INSERT INTO student VALUES (1,'Mei','11A',88),(2,'Sam','11B',71),(3,'Ana','11A',95);
    SELECT name, score FROM student
    WHERE form IN ('11A', '11C') AND score BETWEEN 80 AND 100;
    
    2.3

    NULL

    English

    NULL marks a missing value 缺失值 — nothing was stored in that cell. NULL is not 0 and not an empty string. A comparison with = or <> never matches it; test with IS NULL or IS NOT NULL.

    • WHERE score = NULL returns no rows at all — not even Sam's row.
    • A NULL in arithmetic gives NULL: score + 5 stays NULL for Sam.

    Common mistakes

    • Test for an empty value with IS NULL, never = NULL.
    • In LIKE, % matches any text and _ matches one character: 'A%' means "starts with A".
    • IN (1, 2, 3) is shorter than many ORs; BETWEEN a AND b includes both ends.
    한국어

    NULL은 누락된 값을 나타내며, 해당 셀에는 아무것도 저장되지 않았음을 의미합니다. NULL은 0이 아니며 빈 문자열도 아닙니다. = 또는 <>과의 비교는 절대 일치하지 않으므로, IS NULL 또는 IS NOT NULL을 사용하여 테스트해야 합니다.

    CREATE TABLE student (id INTEGER, name TEXT, score INTEGER);
    INSERT INTO student VALUES (1, 'Mei', 88), (2, 'Sam', NULL), (3, 'Ana', 95);
    SELECT name FROM student WHERE score IS NULL;
    
    CREATE TABLE student (id INTEGER, name TEXT, score INTEGER);
    INSERT INTO student VALUES (1, 'Mei', 88), (2, 'Sam', NULL), (3, 'Ana', 95);
    SELECT name, score FROM student WHERE score IS NOT NULL;
    
    • WHERE score = NULL는 전혀 행을 반환하지 않습니다 — Sam의 행조차도 없습니다.
    • 산술 연산에서 NULL은 NULL을 생성합니다: Sam에 대해 score + 5는 NULL로 남습니다.

    Common mistakes

    • 빈 값에 대해 테스트하려면 IS NULL를 사용하고, 절대 = NULL을 사용하지 마십시오.
    • LIKE에서, %은 임의의 텍스트와 일치하고 _는 하나의 문자와 일치합니다: 'A%'는 "A로 시작"을 의미합니다.
    • IN (1, 2, 3)는 여러 OR보다 짧으며; BETWEEN a AND b는 양쪽 끝을 포함합니다.
  • 3 Sorting & limiting · ⁨정렬 및 제한⁩
    3.1

    ORDER BY 및 LIMIT

    English

    ORDER BY sorts 排序 the result rows. Add DESC for descending 降序 (high to low); the default is ascending 升序 (low to high).

    Sort by more than one column

    List several columns. A tie 平局 in the first column is broken by the next.

    LIMIT (top-N)

    LIMIT n keeps only the first n rows — pair it with ORDER BY for a top-N 前 N 名 list.

    • ORDER BY can also sort by an alias or a calculation: ORDER BY avg_score DESC.
    • Text sorts alphabetically: ORDER BY name runs A → Z.

    Common mistakes

    • ORDER BY sorts ascending by default; add DESC for descending.
    • ORDER BY comes near the end, after WHERE and GROUP BY.
    • LIMIT caps how many rows come back, but only after sorting.
    한국어

    ORDER BY는 결과 행을 정렬합니다. 하강(높은 값에서 낮은 값)으로 정리하려면 DESC을 추가하십시오; 기본값은 상승(낮은 값에서 높은 값)입니다.

    CREATE TABLE student (id INTEGER, name TEXT, score INTEGER);
    INSERT INTO student VALUES (1,'Mei',88),(2,'Sam',71),(3,'Ana',95);
    SELECT name, score FROM student ORDER BY score DESC;
    

    여러 열로 정렬하기

    여러 열을 나열하십시오. 첫 번째 열에서 동점이 발생하면 다음 열로 결정합니다.

    CREATE TABLE student (id INTEGER, name TEXT, score INTEGER);
    INSERT INTO student VALUES (1,'Mei',88),(2,'Sam',88),(3,'Ana',95);
    SELECT name, score FROM student ORDER BY score DESC, name ASC;
    

    LIMIT (상위-N)

    LIMIT n는 처음 n개의 행만 유지합니다 — 상위-N 목록을 만들기 위해 ORDER BY와 함께 사용하십시오.

    CREATE TABLE student (id INTEGER, name TEXT, score INTEGER);
    INSERT INTO student VALUES (1,'Mei',88),(2,'Sam',71),(3,'Ana',95);
    SELECT name, score FROM student ORDER BY score DESC LIMIT 2;
    
    • ORDER BY는 별명이나 계산식으로 정렬할 수도 있습니다: ORDER BY avg_score DESC.
    • 텍스트는 알파벳 순으로 정렬됩니다: ORDER BY name는 A → Z로 실행됩니다.

    Common mistakes

    • 기본값은 오름차순 정렬인 ORDER BY이며, 내림차순으로 정렬하려면 DESC을 추가하세요.
    • ORDER BY는 마지막에near 위치하며, WHERE과 GROUP BY 뒤에 옵니다.
    • LIMIT는 반환되는 행의 수를 제한하지만, 오직 정렬 후에만 적용됩니다.
    ORDER BY는 정렬함; LIMIT는 정렬 후 처음 n개를 유지함
    ORDER BY는 정렬함; LIMIT는 정렬 후 처음 n개를 유지함
  • 4 Aggregates & grouping · ⁨집계 및 그룹화⁩
    4.1

    집계 함수

    English

    An aggregate function 聚合函数 turns many rows into one summary 汇总 value. Wrap an average in ROUND(x, 2) to tidy it.

    Function Gives
    COUNT(*) how many rows
    SUM(col) the total
    AVG(col) the mean average
    MIN(col) / MAX(col) the smallest / largest value
    한국어

    집계 함수는 여러 행을 하나의 요약 값으로 변환합니다. 평균을 ROUND(x, 2)로 감싸서 깔끔하게 만드십시오.

    함수 제공됨
    COUNT(*) 행의 개수
    SUM(col) 합계
    AVG(col) 평균
    MIN(col) / MAX(col) 최소 / 최대 값
    CREATE TABLE student (id INTEGER, name TEXT, form TEXT, score INTEGER);
    INSERT INTO student VALUES (1,'Mei','11A',88),(2,'Sam','11B',71),(3,'Ana','11A',95);
    SELECT COUNT(*), ROUND(AVG(score), 2), MAX(score) FROM student;
    
    4.2

    GROUP BY 및 HAVING

    English

    GROUP BY makes one summary row per group 组. HAVING filters those groups — it is like WHERE, but it runs after grouping.

    Whatever order you write them in, SQL always runs the clauses of a query in the same fixed order:

    Step Clause
    1 FROM (and any JOIN)
    2 WHERE — filter rows
    3 GROUP BY — form groups
    4 HAVING — filter groups
    5 SELECT — compute the output columns
    6 ORDER BY, then LIMIT

    Common mistakes

    • You cannot select a plain column beside an aggregate unless it is in GROUP BY.
    • Filter rows with WHERE (before grouping) and filter groups with HAVING (after).
    • COUNT(*) counts rows; COUNT(col) skips NULLs in that column.
    한국어

    GROUP BY는 그룹마다 하나의 요약 행을 만듭니다. HAVING은 이러한 그룹을 필터링합니다 — WHERE와 유사하지만, 그룹화 후에 실행됩니다.

    CREATE TABLE student (id INTEGER, name TEXT, form TEXT, score INTEGER);
    INSERT INTO student VALUES (1,'Mei','11A',88),(2,'Sam','11B',71),(3,'Ana','11A',95);
    SELECT form, COUNT(*) AS n, ROUND(AVG(score), 2) AS avg_score
    FROM student
    GROUP BY form
    HAVING COUNT(*) > 1;
    
    GROUP BY는 각 값당 하나의 버킷으로 행을 모음; 각 버킷이 하나의 요약 행으로 변함
    GROUP BY는 각 값에 대해 행을 하나의 버킷으로 묶습니다; 각 버킷은 한 줄의 요약 행이 됩니다

    SQL 문장을 어떤 순서로 작성하더라도, 쿼리의 구절들은 항상 동일한 고정된 순서로 실행됩니다:

    단계 구절
    1 FROM (및 JOIN)
    2 WHERE — 행 필터링
    3 GROUP BY — 그룹 형성
    4 HAVING — 그룹 필터링
    5 SELECT — 출력 열 계산
    6 ORDER BY, 이후 LIMIT

    Common mistakes

    • 집계 함수와 함께 일반 열을 선택할 수 있는 것은 GROUP BY에 포함된 경우에만 해당합니다.
    • grouping 전에 WHERE으로 행을 필터링하고, grouping 후에 HAVING으로 그룹을 필터링합니다.
    • COUNT(*)은 행을 세고; COUNT(col)은 해당 열의 NULL 값을 건너뜁니다.
  • 5 Joins · ⁨조인⁩
    5.1

    키 및 관계

    English

    A primary key 主键 uniquely names each row in a table. A foreign key 外键 in one table points to the primary key of another — that builds a relationship 关系 between them.

    한국어

    주요 키(primary key)는 테이블의 각 행을 고유하게 식별합니다. 다른 테이블의 주요 키를 가리키는 외래 키(foreign key)가 하나의 테이블에 존재하면 두 테이블 사이에 관계가 구축됩니다.

    CREATE TABLE class (id INTEGER, name TEXT);
    CREATE TABLE student (id INTEGER, name TEXT, class_id INTEGER);
    INSERT INTO class VALUES (1, 'Maths'), (2, 'Art');
    INSERT INTO student VALUES (1, 'Mei', 1), (2, 'Sam', 2);
    SELECT * FROM student;
    
    5.2

    INNER JOIN

    English

    A join 连接 combines rows from two tables. INNER JOIN ... ON ... keeps rows where the keys match. A short alias 别名 (s, c) keeps the query readable.

    한국어

    join은 두 테이블의 행을 결합합니다. INNER JOIN ... ON ...은 키가 일치하는 행만 유지합니다. 짧은 대명사(s, c)를 사용하면 쿼리를 가독성 있게 유지할 수 있습니다.

    CREATE TABLE class (id INTEGER, name TEXT);
    CREATE TABLE student (id INTEGER, name TEXT, class_id INTEGER);
    INSERT INTO class VALUES (1, 'Maths'), (2, 'Art');
    INSERT INTO student VALUES (1, 'Mei', 1), (2, 'Sam', 2);
    SELECT s.name, c.name AS class
    FROM student s INNER JOIN class c ON s.class_id = c.id;
    
    INNER JOIN은 각 외래 키를 주요 키와 매칭하여 일치하는 행을 결합합니다
    INNER JOIN은 각 외래 키를 주요 키와 매칭하여 일치하는 행을 결합합니다
    5.3

    그룹화와의 join

    English

    Join first, then GROUP BY to summarise across the joined rows.

    한국어

    먼저 join한 후, 결합된 행에 대해 요약하기 위해 GROUP BY을 사용합니다.

    CREATE TABLE class (id INTEGER, name TEXT);
    CREATE TABLE student (id INTEGER, name TEXT, class_id INTEGER);
    INSERT INTO class VALUES (1, 'Maths'), (2, 'Art');
    INSERT INTO student VALUES (1, 'Mei', 1), (2, 'Sam', 2), (3, 'Ana', 1);
    SELECT c.name AS class, COUNT(*) AS n
    FROM student s INNER JOIN class c ON s.class_id = c.id
    GROUP BY c.name;
    
    5.4

    LEFT JOIN

    English

    An INNER JOIN keeps only matched rows. A LEFT JOIN 左连接 keeps every row of the left (first) table; where there is no match, the right table's columns come back as NULL.

    • Sam has no class, but the row still appears — with class as NULL.
    • To find only the unmatched rows, add WHERE c.id IS NULL.

    Common mistakes

    • A join with no ON condition pairs every row with every row (a cross join).
    • Match the foreign key to the primary key: ON orders.customer_id = customers.id.
    • An INNER JOIN drops rows that have no match on the other side; use a LEFT JOIN to keep them.
    한국어

    INNER JOIN은 일치하는 행만 유지합니다. LEFT JOIN은 왼쪽(첫 번째) 테이블의 모든 행을 유지하며, 일치하지 않는 곳에서는 오른쪽 테이블의 열이 NULL로 반환됩니다.

    CREATE TABLE class (id INTEGER, name TEXT);
    CREATE TABLE student (id INTEGER, name TEXT, class_id INTEGER);
    INSERT INTO class VALUES (1, 'Maths'), (2, 'Art');
    INSERT INTO student VALUES (1, 'Mei', 1), (2, 'Sam', NULL);
    SELECT s.name, c.name AS class
    FROM student s LEFT JOIN class c ON s.class_id = c.id;
    
    • Sam에게 수업이 없어도该行仍需出现 — class이 NULL으로 표시됩니다.
    • 일치하지 않는 행만 찾으려면 WHERE c.id IS NULL을 추가하십시오.

    Common mistakes

    • ON 조건이 없는 join은 모든 행을 서로 조합합니다(크로스 조인).
    • 외래 키를 주요 키와 매칭: ON orders.customer_id = customers.id.
    • 양측에서 일치하는 행이 없는 행은 INNER JOIN에서 제거되므로, 이를 유지하려면 LEFT JOIN을 사용하십시오.
  • 6 Modifying data · ⁨데이터 수정⁩
    6.1

    INSERT

    English

    INSERT INTO ... VALUES ... adds new rows 行. Name the columns, then give the values in the same order. (Each block below ends with a SELECT so you can see the result.)

    • INSERT INTO t VALUES (...), (...); adds several rows in one statement.
    한국어

    INSERT INTO ... VALUES ... adds new rows 行. Name the columns, then give the values in the same order. (Each block below ends with a SELECT so you can see the result.)

    CREATE TABLE student (id INTEGER, name TEXT, score INTEGER);
    INSERT INTO student (id, name, score) VALUES (1, 'Mei', 88);
    INSERT INTO student VALUES (2, 'Sam', 71);
    SELECT * FROM student;
    
    • INSERT INTO t VALUES (...), (...); adds several rows in one statement.
    INSERT adds a new row to a table
    INSERT adds a new row to a table
    6.2

    UPDATE

    UPDATE ... SET ... WHERE ... changes existing rows. Always add WHERE, or every row changes.

    CREATE TABLE student (id INTEGER, name TEXT, score INTEGER);
    INSERT INTO student VALUES (1, 'Mei', 88), (2, 'Sam', 71);
    UPDATE student SET score = 75 WHERE name = 'Sam';
    SELECT * FROM student;
    
    6.3

    DELETE

    English

    DELETE FROM ... WHERE ... removes rows. Without WHERE it empties the whole table 表.

    Common mistakes

    • UPDATE and DELETE without a WHERE change every row — always add the WHERE.
    • In INSERT, the values must line up with the column list in order and type.
    • Test a risky DELETE first as a SELECT with the same WHERE.
    한국어

    DELETE FROM ... WHERE ... removes rows. Without WHERE it empties the whole table 表.

    CREATE TABLE student (id INTEGER, name TEXT, score INTEGER);
    INSERT INTO student VALUES (1, 'Mei', 88), (2, 'Sam', 71);
    DELETE FROM student WHERE score < 80;
    SELECT * FROM student;
    

    Common mistakes

    • UPDATE and DELETE without a WHERE change every row — always add the WHERE.
    • In INSERT, the values must line up with the column list in order and type.
    • Test a risky DELETE first as a SELECT with the same WHERE.
  • 7 Defining tables · ⁨테이블 정의⁩
    7.1

    CREATE TABLE & 데이터 유형

    English

    CREATE TABLE defines a table's schema 表结构: the column names and their data types 数据类型. The main SQLite types are INTEGER, TEXT, and REAL (a decimal number).

    한국어

    CREATE TABLE은 테이블의 스키마를 정의합니다: 열 이름과 그들의 데이터 유형입니다. SQLite의 주요数据类型은 INTEGER, TEXT, 그리고 REAL(소수점 숫자)입니다.

    CREATE TABLE student (id INTEGER, name TEXT, score REAL);
    INSERT INTO student VALUES (1, 'Mei', 88.5);
    SELECT * FROM student;
    
    CREATE TABLE은 열 이름과 유형을 명시합니다
    CREATE TABLE은 열 이름과 유형을 명시합니다
    7.2

    키 및 제약 조건

    English

    A constraint 约束 is a rule on a column: PRIMARY KEY (a unique id), NOT NULL (must have a value), UNIQUE, and DEFAULT (a fallback value).

    Declare a foreign key with REFERENCES — it records that the column points at another table's primary key:

    • The long form is FOREIGN KEY (class_id) REFERENCES class(id) on its own line.
    한국어

    제약 조건(constraint)은 열에 적용되는 규칙입니다: PRIMARY KEY(유일 ID), NOT NULL(값 필수), UNIQUE, 그리고 DEFAULT(기본값 fallback).

    CREATE TABLE student (
        id INTEGER PRIMARY KEY,
        name TEXT NOT NULL,
        score INTEGER DEFAULT 0
    );
    INSERT INTO student (id, name) VALUES (1, 'Mei');
    SELECT * FROM student;
    

    외래 키를 REFERENCES으로 선언하세요 — 이는 해당 열이 다른 테이블의 주요 키를 가리킴을 기록합니다:

    CREATE TABLE class (id INTEGER PRIMARY KEY, name TEXT);
    CREATE TABLE student (
        id INTEGER PRIMARY KEY,
        name TEXT NOT NULL,
        class_id INTEGER REFERENCES class(id)
    );
    INSERT INTO class VALUES (1, 'Maths');
    INSERT INTO student VALUES (1, 'Mei', 1);
    SELECT s.name, c.name AS class
    FROM student s INNER JOIN class c ON s.class_id = c.id;
    
    • 긴 형식은 FOREIGN KEY (class_id) REFERENCES class(id)을 단독 줄에 표기합니다.
    7.3

    ALTER TABLE

    English

    ALTER TABLE ... ADD COLUMN ... changes the schema of a table that already exists. A DEFAULT fills the new column in the old rows.

    • ALTER TABLE student RENAME TO pupil; renames the whole table.
    • DROP TABLE student; deletes the table completely — structure and data.

    Common mistakes

    • Every column needs a data type (e.g. INTEGER, TEXT).
    • A PRIMARY KEY must be unique and cannot be NULL.
    • A foreign key value must exist in the table it points to.
    한국어

    ALTER TABLE ... ADD COLUMN ...은 기존 테이블의 스키마를 변경합니다. DEFAULT은 기존 행의 새 열을 채웁니다.

    CREATE TABLE student (id INTEGER, name TEXT);
    INSERT INTO student VALUES (1, 'Mei');
    ALTER TABLE student ADD COLUMN score INTEGER DEFAULT 0;
    SELECT * FROM student;
    
    • ALTER TABLE student RENAME TO pupil;은 전체 테이블 이름을 변경합니다.
    • DROP TABLE student;은 테이블을 완전히 삭제합니다 — 구조 및 데이터까지.

    Common mistakes

    • 모든 열은 데이터 타입을 가져야 합니다(예: INTEGER, TEXT).
    • PRIMARY KEY는 유일해야 하며 NULL일 수 없습니다.
    • 외래 키 값은 그 가리키는 테이블에 존재해야 합니다.
  • 8 Database design · ⁨데이터베이스 설계⁩
    8.1

    관계 및 ER 다이어그램

    English

    Tables connect through relationships 关系. One-to-many 一对多 is the most common: one class has many students. Many-to-many 多对多 needs a join table 连接表 in the middle. An entity-relationship diagram 实体关系图 (ER diagram) draws each entity 实体 as a box and each relationship as a line.

    Relationship Example
    one-to-one a person and their passport
    one-to-many a class and its students
    many-to-many students and clubs

    The join table holds one row per link. Here Mei is in two clubs, and Chess has two members:

    한국어

    테이블은 관계를 통해 연결됩니다. 일대다关系는 가장 흔합니다: 한 수업에 많은 학생이 있습니다. 다대다关系는 중간에 결합 테이블이 필요합니다. 엔티티-관계 다이어그램(ER diagram)은 각 엔티티를 상자로, 각 관계를 선으로 그립니다.

    관계 예시
    일대일 사람과 여권
    일대다 수업과 학생들
    다대다 학생들과 동아리
    '다' 측이 외래 키를 포함하며, 다대다 링크에는 결합 테이블이 필요합니다
    '다' 측이 외래 키를 포함하며, 다대다 링크에는 결합 테이블이 필요합니다

    결합 테이블은 각 링크당 한 행을 가집니다. 여기 Mei는 두 개의 동아리에 속해 있고, Chess는 두 명의 멤버가 있습니다:

    CREATE TABLE student (id INTEGER PRIMARY KEY, name TEXT);
    CREATE TABLE club (id INTEGER PRIMARY KEY, name TEXT);
    CREATE TABLE membership (student_id INTEGER, club_id INTEGER);
    INSERT INTO student VALUES (1, 'Mei'), (2, 'Sam');
    INSERT INTO club VALUES (1, 'Chess'), (2, 'Art');
    INSERT INTO membership VALUES (1, 1), (1, 2), (2, 1);
    SELECT s.name, c.name AS club
    FROM membership m
    INNER JOIN student s ON m.student_id = s.id
    INNER JOIN club c ON m.club_id = c.id;
    
    8.2

    정형화

    English

    Normalisation 范式化 organises tables to avoid redundancy 冗余 (the same data repeated) and the update mistakes it causes. The first three normal forms 范式:

    • 1NF: every cell holds one atomic 原子 value — no lists inside a cell.
    • 2NF: no column depends on only part of a composite key 复合主键.
    • 3NF: no column depends on another non-key column.
    Unnormalised (bad) Normalised (better)
    student(name, club1, club2) student(name) + membership(student, club)

    Common mistakes

    • Split repeating groups into their own table (normalisation) instead of many similar columns.
    • Each table should describe ONE kind of thing.
    • Link tables with a foreign key that points to another table's primary key.
    한국어

    정규화(normalisation)는 중복(동일한 데이터 반복)을 피하고 이로 인한 업데이트 오류를 방지하기 위해 테이블을 정리합니다. 첫 세 가지 정규화 형태:

    • 1NF: 모든 셀은 단일 원자적(value) 값을 가져야 합니다 — 셀 내에 목록이 있어서는 안 됩니다.
    • 2NF: 열이 복합 키의 일부에만 의존해서는 안 됩니다.
    • 3NF: 열이 다른 비키 열에 의존해서는 안 됩니다.
    정규화되지 않음(나쁨) 정규화됨(더 좋음)
    student(name, club1, club2) student(name) + membership(student, club)

    Common mistakes

    • 반복되는 그룹을 여러 유사한 열 대신 별도의 테이블로 분리하십시오(정규화).
    • 각 테이블은 ONE 종류의 사물을 묘사해야 합니다.
    • 다른 테이블의 주요 키를 가리키는 외래 키로 테이블을 연결하십시오.

Log in or create account · ⁨로그인 또는 계정 만들기⁩

IGCSE, A-Level & AP