DATA-06 · DATA SCIENCE

결합·집계·SQL과 키의 검증Joins, aggregation, SQL and key validation

원행 관계·NULL·집계 분모를 실제 코드로 추적하기Trace source relationships, NULLs and aggregation denominators with actual code

실습 6종 · 풀이 포함 연습문제 60개6 labs · 60 exercises with solutions

기초Foundations

1. 붙이기 전에 한 행의 뜻을 적는다1. State what a row means before joining

학생 이름표와 시험 점수표를 붙인다고 생각해 봅시다. “첫 줄끼리” 붙이면 두 표의 순서가 바뀌는 순간 다른 학생의 점수를 가져올 수 있습니다. 먼저 각 표에서 한 행이 무엇인지, 어떤 값으로 같은 대상을 찾는지, 한 행에 몇 개가 대응할 수 있는지 적습니다.

이 장은 작은 이름표에서 시작해 실제 720개 국가년, 3,613명 원행, 410개 점포 원행을 결합합니다. 키·조합 수·NULL·집계 분모를 확인한 뒤 SQL로 같은 관계를 표현합니다. 큰 결과표가 더 많은 관측을 뜻하는 것은 아닙니다.

브라우저는 실제 새 프로세스에서 실행해 보관한 결과를 선택합니다. Python은 네이티브 SQLite를 실행했고 R은 명시한 base R 대응 계산을 했습니다. 이 둘을 같은 SQL 실행이라고 부르지 않으며, 화면에서 임의 SQL이나 Python/R을 실행하지 않습니다.

Imagine joining student labels to test scores. Attaching “first row to first row” can assign a score to the wrong student as soon as one table is reordered. State each row’s unit, its matching fields and the number of possible counterparts first.

Start with toy labels, then examine 720 actual country-years, 3,613 person records and 410 establishment records. Check keys, combinations, NULLs and aggregation denominators before expressing the relationship in SQL. A larger output is not necessarily more observed information.

The browser selects archived fresh-process runs. Python actually ran native SQLite; R ran explicitly stated base-R counterparts. These are distinct execution routes, and this page executes no arbitrary SQL or Python/R.

기초Foundations

2. 단위와 관계를 두 표에 각각 선언한다2. Declare units and relationships for both tables

가정 왼쪽 표는 학생당 한 행이고 오른쪽 표는 학생·시험당 한 행입니다. 학생 한 명의 시험이 세 개라면 학생 한 행이 시험 세 행과 연결되는 것이 정상입니다. 이때 출력의 한 행은 더 이상 단순한 학생 한 명이 아니라 학생·시험 대응입니다.

반대로 국가의 GDP와 기대수명을 같은 연도로 비교하려면 두 표 모두 국가년 단위여야 합니다. 국가 이름이 같아도 연도가 다르면 원하는 관계가 아닙니다. 원행 추적 번호와 실제 분석 단위도 구별합니다. 번호가 고유하다고 영구 개체 정체나 통계적 독립성이 증명되지는 않습니다.

Suppose the left table has one row per student and the right has one row per student-exam. Three exams for one student correctly produce three matches. An output row now represents a student-exam correspondence rather than merely a student.

For a same-year comparison of GDP and life expectancy, both inputs must use country-years. Equal country labels with different years do not establish that intended relationship. A unique archive-row number traces a source record without proving permanent entity identity or statistical independence.

기초Foundations

3. 키는 원하는 범위의 유일성 계약이다3. A key is a uniqueness contract for a stated scope

이 장의 선언 키는 값이 있고 각 행을 구별해야 합니다. 가정 코드 A,B는 두 행을 구별하지만 A,A는 그렇지 않습니다. 유일성은 파일·버전·대상 범위에 대한 성질입니다. 한 학교에서 고유한 학번이 다른 학교 자료까지 자동으로 구별하지는 않습니다.

관계형 용어에서 후보키는 행을 구별하는 최소 속성 집합이고 기본키는 그중 선택한 것입니다. 실제 데이터베이스 제품의 제약 동작은 별도로 확인합니다. 이번 SQLite 예는 PRIMARY KEY에 더해 NOT NULL을 명시하여 우리가 요구하는 가용성 계약을 확실히 검사합니다.

The declared keys in this chapter must be available and distinguish records. Toy codes A, B do; A, A do not. Uniqueness belongs to a file, version and scope. A student number unique within one school need not identify records across schools.

A candidate key is a minimal identifying attribute set; a primary key is a selected candidate. Database products implement constraints with their own details. Our SQLite examples explicitly add NOT NULL alongside PRIMARY KEY to enforce the availability contract we intend.

기초Foundations

4. 국가와 연도를 함께 쓰는 복합키4. Use country and year together as a composite key

가정 두 행 (A,2023),(A,2024)에서 국가 A는 반복되지만 국가·연도 쌍은 다릅니다. 국가 코드만 키로 선언하면 실패하고 두 필드를 함께 선언하면 이 예는 통과합니다. 쌍의 각 성분이 따로 고유할 필요는 없습니다.

문자열을 구분자 없이 이어 키를 만들면 (AB,C)와 (A,BC)가 같은 문자열 ABC가 될 수 있습니다. 데이터베이스의 두 열 제약이나 언어의 구조 있는 튜플로 쌍을 비교하세요. 원문에 없는 규칙으로 대소문자·앞자리 0을 지우기 전에는 코드의 실제 의미와 충돌 여부부터 확인합니다.

In toy rows (A,2023),(A,2024), country A repeats but the country-year pairs differ. A country-only key fails; the two-field key passes here. Neither component must be individually unique.

Concatenating without a delimiter can merge (AB, C) and (A, BC) into the same text ABC. Use a two-column constraint or structured tuples. Before deleting leading zeros or normalizing case, check the source code’s meaning and possible collisions rather than inventing an identifier rule.

기초Foundations

5. 실제 키 검사 코드와 오류를 읽는다5. Read actual key-check code and failures

다음은 실제 Python·SQLite 성공 예의 전체 코드와 출력입니다. 새 메모리 데이터베이스를 만들고 스키마를 선언한 다음 ? 자리에 값을 바인딩합니다. 두 A를 넣는 별도 고정 예는 유일성 오류, NULL 키를 넣는 예는 가용성 오류로 실제 실패했습니다.

import sys
sys.stdout.reconfigure(encoding="utf-8")
sys.stderr.reconfigure(encoding="utf-8")
import json,sqlite3
db=sqlite3.connect(":memory:")
db.execute('CREATE TABLE records(iso TEXT NOT NULL PRIMARY KEY,year INTEGER NOT NULL);')
rows=[['A', 2023], ['B', 2024]]
db.executemany("INSERT INTO records VALUES(?,?)",rows)
print(json.dumps(dict(keyColumns=['iso'],rows=rows,declaredKeyPassed=True,observationalTruthCertified=False)))
db.close()
{"keyColumns": ["iso"], "rows": [["A", 2023], ["B", 2024]], "declaredKeyPassed": true, "observationalTruthCertified": false}

R 대응 예는 anyNA와 anyDuplicated로 선언 조건을 확인하고 실패 시 stop을 호출합니다. SQL 엔진의 제약과 R 코드의 조건 검사는 다른 구현입니다. 성공 종료는 선언한 키 검사 통과이지 현실의 개체 정체를 인증한 결과가 아닙니다.

This is the complete source and output of an actual successful Python/SQLite run. It creates a new in-memory database, declares a schema and binds values to ? placeholders. Separate fixed examples actually fail for repeated A keys and a NULL key.

import sys
sys.stdout.reconfigure(encoding="utf-8")
sys.stderr.reconfigure(encoding="utf-8")
import json,sqlite3
db=sqlite3.connect(":memory:")
db.execute('CREATE TABLE records(iso TEXT NOT NULL PRIMARY KEY,year INTEGER NOT NULL);')
rows=[['A', 2023], ['B', 2024]]
db.executemany("INSERT INTO records VALUES(?,?)",rows)
print(json.dumps(dict(keyColumns=['iso'],rows=rows,declaredKeyPassed=True,observationalTruthCertified=False)))
db.close()
{"keyColumns": ["iso"], "rows": [["A", 2023], ["B", 2024]], "declaredKeyPassed": true, "observationalTruthCertified": false}

The base-R counterpart explicitly checks anyNA and anyDuplicated, then calls stop on failure. SQL constraints and R conditions are different implementations. A successful exit establishes the declared check, not real-world entity identity.

기초Foundations

6. 왼쪽 고유성만으로 모든 관계를 보증할 수 없다6. Left uniqueness does not establish every relationship

왼쪽 학생 키가 고유해도 오른쪽 시험 표에는 같은 학생 키가 여러 번 나올 수 있습니다. 원하는 관계가 일대일이라면 양쪽 키의 고유성과 미일치 수를 모두 확인해야 합니다. 원하는 관계가 일대다라면 오른쪽 반복은 정상일 수 있지만 각 시험의 별도 키가 필요할 수 있습니다.

외래키는 허용한 참조 대상의 존재를 제한하는 개념입니다. 이번 조인 실습이 실제 외래키 제약을 선언·강제했다고 하지 않습니다. 대응 수·가용성·업무상 관계를 분리해 검사하며, 엔진이 표를 붙였다는 사실만으로 그 관계가 옳다고 결론내리지 않습니다.

A unique student key on the left can match several exam records on the right. For an intended one-to-one relationship, inspect both sides’ uniqueness and unmatched counts. In a one-to-many relationship, repeated student keys on the right can be correct while exams need their own identifiers.

A foreign-key constraint concerns permitted references to another table. These join demonstrations do not claim to declare and enforce actual foreign-key constraints. Inspect multiplicity, availability and substantive relationships separately; an engine’s ability to combine rows does not establish a valid linkage.

기초Foundations

7. 키의 미관측과 값의 미관측은 다른 계약이다7. Missing keys and missing values have different contracts

학생 키 B가 있고 점수만 NULL이면 “B라는 기록은 있지만 점수가 미관측”입니다. 오른쪽 표에 B가 아예 없으면 “그 표에서 B 키에 대응하는 기록이 없음”입니다. 둘은 점수 칸이 비어 보일 수 있어도 다른 상태입니다.

원키가 NULL인 경우에는 이 장의 키 계약을 먼저 실패시킵니다. 일반 SQL의 = 조인은 NULL끼리 참으로 일치시키지 않으며, R의 merge 기본 NA 대응과 같다고 가정하지 않습니다. NULL 허용 키나 별도의 NULL 안전 비교는 명시적으로 다른 설계로 다뤄야 합니다.

If right key B exists with a NULL score, its record exists while its value is unavailable. If B is absent from the right table, no right record has that key. Both can display an empty score, but they are different states.

A NULL source key fails the contract used here. Ordinary SQL equality joins do not make NULL equal NULL; do not assume base R’s default NA matching is identical. Nullable keys or explicitly NULL-safe comparisons require a separately declared design.

기초Foundations

8. 실습 A · 같은 입력과 다른 키 선언8. Lab A · fixed inputs and different key contracts

정상 코드·반복 코드·NULL 키·복합키 가정 예를 먼저 예상하세요. 복합키 예의 (A,2023),(A,2024)는 국가 반복이 있어도 쌍으로는 고유합니다. 실제 오류 메시지와 종료 상태를 함께 확인하고, Python·SQLite와 base R의 구현을 비교합니다.

실패는 고정 검사를 실제로 실행한 결과입니다. 오류를 숨겨 성공한 표처럼 그리지 않습니다. 수정할 입력과 비교 범위를 정한 뒤 새 코드로 재실행해야 하며, 화면 선택은 보관 기록 조회입니다.

Predict the valid, repeated, NULL-key and composite-key examples. The pairs (A,2023),(A,2024) remain unique despite repeating A. Read actual error messages with exit status, and compare the distinct Python/SQLite and base-R implementations.

Failures are retained actual outcomes rather than fabricated successful tables. A correction needs a defined input change and a fresh real run. Choosing a record here only retrieves an archived execution.

기초Foundations

9. 일치 표를 손으로 먼저 만든다9. Build a match table by hand first

가정 왼쪽은 원행 1:A,2:B,3:C이고 오른쪽은 원행 1:A값 10,2:A값 30,3:B값 20입니다. A는 두 번, B는 한 번 일치하고 C는 일치하지 않습니다. 세 출력 짝은 (1,1),(1,2),(2,3)입니다. 이 원행 쌍을 적으면 값만 보는 것보다 증폭을 쉽게 발견합니다.

조인의 기본 작업은 두 표에서 조건을 만족하는 행 쌍을 찾는 것입니다. 동일한 값이 있다고 원행 쌍을 하나로 축약하지 않습니다. 출력에 왼쪽·오른쪽 원행 키를 나란히 남기고, 관측을 잘못 연결한 짝이 없는지 검사합니다.

Toy left source rows are 1: A,2: B,3: C; right rows are 1: A with value 10,2: A with value 30,3: B with value 20. A matches twice, B once and C not at all. The matching source-position pairs are (1,1),(1,2),(2,3).

A join finds pairs satisfying its condition. Equal displayed values do not collapse distinct source pairs. Retain both source keys side by side; this exposes multiplicity and incorrect linkage more clearly than inspecting values alone.

기초Foundations

10. INNER JOIN은 조건을 만족하는 짝을 남긴다10. INNER JOIN retains matching pairs

앞 가정에서 INNER JOIN은 세 짝만 남깁니다. 일치가 없는 C는 출력에 없고 A의 왼쪽 원행은 두 번 나옵니다. 출력 행 수가 왼쪽 원행 수와 우연히 3으로 같지만 같은 원행 집합이 보존된 것은 아닙니다.

행 수 일치만 확인하면 A의 증폭과 C의 소실이 상쇄되어 오류를 놓칠 수 있습니다. 각 원행의 대응 수와 미일치 키를 함께 확인하세요. 조인 조건에 들어간 단위가 학생인지 학생·시험인지에 따라 이 결과가 정상인지 판단합니다.

INNER JOIN retains the three matching pairs. C disappears while the left A row occurs twice. The result happens to have the same count as the three-row left table, but it does not preserve the same source-row set.

A count-only check can miss amplification of A offset by loss of C. Inspect matches per source row and unmatched keys together. Whether this result is intended depends on the declared student or student-exam unit.

기초Foundations

11. LEFT JOIN은 각 왼쪽 행을 적어도 한 번 남긴다11. LEFT JOIN retains every left row at least once

같은 가정의 LEFT JOIN은 세 일치 짝에 C의 NULL 확장 한 행을 더해 4행입니다. 오른쪽 원행·값 칸은 NULL로 보충됩니다. 각 왼쪽 행을 남긴다는 말은 정확히 한 번 남긴다는 말과 다릅니다. A는 여전히 두 행입니다.

이 설명은 조건 계산 뒤 추가 WHERE로 행을 없애기 전의 조인 결과에 해당합니다. 뒤에서 NULL 값 조건으로 필터하면 C가 없어질 수 있습니다. “LEFT니까 원래 표가 그대로다”라고 요약하지 말고 어떤 단계의 결과인지 적습니다.

LEFT JOIN adds one NULL-extended C row to the three matches, producing four rows. The right source key and value are NULL. Preserving each left row does not mean preserving it exactly once: A still occurs twice.

This statement concerns the join result before a later WHERE filter. A predicate on the right value can subsequently remove C. Name the processing stage rather than claiming that a left join leaves the original table unchanged.

기초Foundations

12. SQL의 별칭과 열 선택을 읽는다12. Read SQL aliases and explicit columns

다음은 실제 가정 일대다 LEFT 실행에서 사용한 SQL입니다. l과 r는 표 별칭이고 l.k=r.k가 대응 조건입니다. 양쪽 원행을 SELECT에 남겨 어떤 짝인지 보며, 마지막 ORDER BY는 표시 순서를 명시합니다. 전체 실행 코드는 실습에서 내려받습니다.

SELECT l.lrow,l.k,r.rrow,r.value FROM left_records l LEFT JOIN right_records r ON l.k=r.k ORDER BY l.lrow,r.rrow;

가정 R 대응은 merge(...,by="k",all.x=TRUE,sort=FALSE) 뒤 원행 쌍으로 명시적으로 정렬합니다. sort=FALSE 자체가 원래 순서를 보증하는 것은 아닙니다. 이 예의 키에는 결측이 없으므로 기본 NA 매칭 차이를 숨겨 쓰지 않습니다.

This SQL was used in the actual toy one-to-many LEFT run. The aliases l and r name the tables; l.k=r.k states the match. Select both source positions, then explicitly order the displayed pairs. Download the complete driver in the lab.

SELECT l.lrow,l.k,r.rrow,r.value FROM left_records l LEFT JOIN right_records r ON l.k=r.k ORDER BY l.lrow,r.rrow;

The R counterpart uses merge(...,by="k",all.x=TRUE,sort=FALSE) and explicitly sorts by both source positions afterward. The option sort=FALSE does not itself promise original order. Toy keys are nonmissing, avoiding an unacknowledged NA-matching difference.

심화Extension

13. 대응 수의 곱으로 출력 행을 센다13. Count result rows from products of multiplicities

선택 심화입니다. 결측 없는 키 k의 왼쪽 등장 수를 Lₖ, 오른쪽 등장 수를 Rₖ라고 합시다. 일반 등호 INNER 조인에서는 k마다 모든 왼쪽·오른쪽 짝이 생기므로 LₖRₖ행입니다. 키별 짝 집합은 서로 겹치지 않아 합할 수 있습니다.

Ninner=∑kLkRkNleft=∑k:Lk>0Lkmax⁡(1,Rk)\begin{gathered}N_{\rm inner}=\sum_k L_kR_k\\N_{\rm left}=\sum_{k:L_k>0}L_k\max(1,R_k)\end{gathered}

두 번째 식은 LEFT 조인 자체의 행 수입니다. 오른쪽 일치가 없으면 왼쪽 각 행마다 한 NULL 확장 행이 생깁니다. 결측 키·추가 조건·후속 WHERE가 있으면 그 의미에 맞춰 짝과 제외를 다시 세어야 합니다.

Optional university connection: for nonmissing equality keys, let Lₖ and Rₖ be left and right multiplicities. Every left-right pair with key k contributes, giving LₖRₖ rows. Distinct keys partition those pairs.

Ninner=∑kLkRkNleft=∑k:Lk>0Lkmax⁡(1,Rk)\begin{gathered}N_{\rm inner}=\sum_k L_kR_k\\N_{\rm left}=\sum_{k:L_k>0}L_k\max(1,R_k)\end{gathered}

The second formula concerns the LEFT join itself: a zero right multiplicity contributes one NULL-extended row per left row. Missing keys, additional predicates and later WHERE filters require corresponding adjustments to the count.

기초Foundations

14. 다대다의 증폭은 표본 수 증가가 아니다14. Many-to-many amplification is not a larger sample

가정 왼쪽 A가 2행, 오른쪽 A가 3행이면 A만 6개 짝입니다. 이것이 원래 6명의 독립된 사람을 관측했다는 뜻은 아닙니다. 관계가 정말 수강생·과제 대응이라면 필요할 수 있지만 한 사람의 두 시점을 붙이는 목적이라면 잘못된 키일 수 있습니다.

실제 국가 표는 국가당 45년입니다. 두 720행 표를 ISO만으로 붙이면 국가당 45×45, 총 16×45²=32,400조합입니다. 같은 국가·같은 연도 조건이면 720행입니다. 31,680개의 추가 조합은 새 관측을 얻은 것이 아닙니다.

Two left A rows and three right A rows produce six A pairs. That does not mean six independent people were observed. Such combinations can be intended for student-assignment relationships while being invalid for matching two waves of one person.

The actual country tables contain 45 years per country. Joining only on ISO gives 16×45²=32,400 combinations; joining the same ISO and year gives 720 rows. The 31,680 additional combinations are not new observations.

심화Extension

15. 조인이 평균에 암묵적 가중치를 줄 수 있다15. A join can implicitly reweight a mean

왼쪽 값 A=0,B=10을 한 번씩 관측했다면 평균은 5입니다. 오른쪽 대응 수가 A에 3개, B에 1개면 조인 후 왼쪽 값을 평균한 결과는 (0+0+0+10)/4=2.5입니다. 원값을 고치지 않아도 대응 수가 가중치를 바꿨습니다.

일반적으로 왼쪽 i행의 값 yᵢ를 비음수 정수 mᵢ번 반복하고 전체 출력 수 Σᵢmᵢ>0이라고 합시다. 출력 평균은 mᵢ를 가중치로 둔 평균입니다. 모든 mᵢ가 같은 양수이면 원 평균과 같지만, 값이 우연히 같아도 대응 수가 같다는 뜻은 아닙니다. 원래 표적이 행 균등인지 사건 균등인지 먼저 정합니다.

yˉjoined=∑imiyi∑imi\bar y_{\rm joined}=\frac{\sum_i m_i y_i}{\sum_i m_i}

Left values A=0, B=10 have mean five. If right matches repeat A three times and B once, the mean of the left value after joining is 2.5. Match multiplicities changed the weights without editing any original value.

Suppose source row i with value yᵢ appears a nonnegative integer mᵢ times and Σᵢmᵢ>0. The output mean is multiplicity weighted. Equal positive multiplicities preserve the mean; accidental mean agreement does not prove equal weights. First decide whether the target weights original rows or matched events equally.

yˉjoined=∑imiyi∑imi\bar y_{\rm joined}=\frac{\sum_i m_i y_i}{\sum_i m_i}
기초Foundations

16. 실습 B · 원행 짝과 미일치를 함께 본다16. Lab B · inspect source pairs and unmatched rows

고정 일대일·일대다·다대다 가정과 INNER/LEFT를 바꿉니다. 먼저 결과 행 수와 C의 보존 여부를 예상하고 두 원행 키를 보세요. 일대다 INNER의 3행과 원 왼쪽 3행은 행 수만 같고 구성은 다릅니다.

Python·SQLite와 base R의 보관 결과를 비교하되 구현 언어와 SQL 실행을 구분합니다. 정렬은 실제 선언한 원행 쌍 순서이며, 화면의 예상 메모는 실행되지 않습니다.

Choose fixed one-to-one, one-to-many or many-to-many inputs and INNER/LEFT. Predict the result count and preservation of C, then inspect both source keys. Three one-to-many INNER rows need not preserve the three original left records.

Compare archived Python/SQLite and base-R results while distinguishing their execution routes. Display order follows explicit source-position ordering; prediction notes are never executed.

기초Foundations

17. 같은 빈 칸에서 서로 다른 두 경로를 찾는다17. Find two different paths to the same empty-looking cell

가정 왼쪽 키는 A,B,C이고 오른쪽에는 A값 10,B값NULL만 있습니다. B는 오른쪽에 있지만 값이 없고 C는 오른쪽 키 자체가 없습니다. LEFT 결과의 B와 C는 값 칸이 모두 NULL입니다. 값만 SELECT하면 두 상태를 구별하기 어렵습니다.

오른쪽의 가용한 고유 키를 함께 남기면 B는 오른쪽 키 B, C는 NULL로 구별됩니다. 이것은 오른쪽 키가 원래 가용하다는 계약을 전제로 합니다. 원키도 NULL일 수 있다면 별도 존재 표지와 원행 계약이 필요합니다.

Toy left keys are A, B, C. The right table contains A with value 10 and B with value NULL. B has a right record with an unavailable value; C has no right key. Both value cells are NULL after LEFT JOIN.

Retain an available right identifier: B has right key B, while C has NULL. This diagnostic relies on a nonmissing original right-key contract. If original keys can also be NULL, use an independently declared presence marker and record contract.

기초Foundations

18. SQL 조건은 참·거짓·미지로 나뉜다18. SQL predicates distinguish true, false and unknown

여기서 일반 등호 비교 NULL=5와 NULL=NULL은 참이 아니라 미지입니다. WHERE는 참인 행만 남기므로 미지인 행도 남기지 않습니다. NULL을 찾는 조건은 IS NULL이고 값이 있는 조건은 IS NOT NULL입니다.

NULL이 모든 SQL 문맥에서 똑같이 비교된다고 확장하지 않습니다. SQLite의 GROUP BY나 DISTINCT는 NULL들을 같은 그룹으로 다룰 수 있지만, 그것이 일반 등호가 참이라는 뜻은 아닙니다. “NULL은 0”이나 “NULL은 아무 문자열”이라는 임의 대체도 하지 않습니다.

Ordinary comparisons NULL=5 and NULL=NULL yield unknown rather than true. WHERE retains only true predicates, so unknown rows are discarded too. Use IS NULL to test missingness and IS NOT NULL to test availability.

Do not extend ordinary equality to every SQL context. SQLite grouping and DISTINCT can treat NULLs together without making ordinary NULL equality true. NULL is neither an observed zero nor an arbitrary replacement string.

기초Foundations

19. ON의 오른쪽 조건은 무엇과 일치할지 바꾼다19. A right-side ON predicate changes which pairs match

앞 가정에서 조인 조건을 키 일치와 r.value>=5로 함께 둡니다. A는 값 10으로 일치합니다. B의 원키는 있지만 NULL값의 조건이 참이 아니므로 일치하지 않고, C도 대응 키가 없습니다. LEFT는 B,C에 각각 NULL 확장 행을 만듭니다.

결과는 3행이고 오른쪽 키가 NULL인 행은 2개입니다. 그러나 원 오른쪽에 키가 없는 대상은 C 하나뿐입니다. NULL 확장 수를 원표의 키 부재 수로 곧바로 읽으면 틀립니다. 실습은 원키 존재 표지와 조인 결과를 별도 열로 보여 줍니다.

SELECT l.lrow,l.k,r.rkey,r.value FROM left_records l LEFT JOIN right_records r ON l.k=r.rkey AND r.value>=5 ORDER BY l.lrow;

Add r.value>=5 to the ON key condition. A matches with value 10. Original key B exists, but its NULL-valued predicate is not true; C has no right key. LEFT JOIN produces NULL-extended rows for both B and C.

The result has three rows, two with a NULL right key. Yet only C lacks a key in the original right table. NULL-extension counts do not directly measure original key absence. The lab displays original key presence separately from the join output.

SELECT l.lrow,l.k,r.rkey,r.value FROM left_records l LEFT JOIN right_records r ON l.k=r.rkey AND r.value>=5 ORDER BY l.lrow;
기초Foundations

20. WHERE의 오른쪽 조건은 이미 만든 행을 줄인다20. A right-side WHERE predicate filters the joined rows

이제 키만으로 LEFT 조인한 뒤 WHERE r.value>=5를 둡니다. 조인 직후 A10,BNULL,CNULL인 3행에서 A만 남습니다. B,C의 조건은 미지이므로 WHERE가 제외합니다. 같은 글자의 조건을 옮겼어도 결과는 ON의 3행과 다릅니다.

이 설명은 결과 의미를 이해하는 논리적 순서입니다. 실제 데이터베이스 최적화기가 반드시 이 순서대로 중간 표를 물리적으로 만들었다는 주장은 아닙니다. 조건 이동의 동등성을 증명하려면 조인 종류와 NULL·미일치 경계를 확인해야 합니다.

SELECT l.lrow,l.k,r.rkey,r.value FROM left_records l LEFT JOIN right_records r ON l.k=r.rkey WHERE r.value>=5 ORDER BY l.lrow;

Instead, first LEFT JOIN on the key and then use WHERE r.value>=5. The conceptual intermediate rows A10, BNULL, CNULL shrink to A alone. B and C yield unknown and are discarded. Moving the same textual predicate changes three rows into one.

This is a logical explanation of result semantics, not a claim about an optimizer’s physical execution order. Establishing equivalence of predicate movement requires the join type and NULL/unmatched boundaries.

SELECT l.lrow,l.k,r.rkey,r.value FROM left_records l LEFT JOIN right_records r ON l.k=r.rkey WHERE r.value>=5 ORDER BY l.lrow;
기초Foundations

21. IS NULL과 잘못된 = NULL을 비교한다21. Compare IS NULL with an incorrect = NULL test

키만으로 붙인 표에 WHERE r.value IS NULL을 적용하면 B와 C 두 행입니다. “오른쪽 키가 없는 행만”을 원하면 이 결과는 너무 넓습니다. 오른쪽 비결측 키 또는 존재 표지의 NULL을 확인해야 합니다.

반면 WHERE r.value=NULL은 이 가정에서 0행입니다. 원표에 NULL이 없어서가 아니라 조건이 참이 되지 않기 때문입니다. 출력 0행과 원자료의 결측 0개를 혼동하지 마세요. SQL이 오류 없이 실행되는 것과 원하는 질문을 표현한 것은 다릅니다.

Applying WHERE r.value IS NULL after the key-only join returns B and C. It is too broad for the question “which left keys are absent on the right?” Test a nonmissing right identifier or declared presence marker instead.

In contrast, WHERE r.value=NULL returns zero rows in this example because the predicate is never true. It does not show that the source has no NULLs. A query can run successfully while answering the wrong question.

기초Foundations

22. R의 NA 처리와 SQL 의미를 명시적으로 연결한다22. Connect R NA handling to SQL semantics explicitly

base R의 merge 기본 동작은 NA 키끼리 일치시킬 수 있어 일반 SQL 등호 조인과 같지 않습니다. 한 열 키의 경우 incomparables=NA 같은 명시 규칙을 검토할 수 있지만, 모든 복합키 문제에 옵션 하나를 그대로 적용한다고 일반화하지 않습니다.

이번 가정 프로그램의 키는 모두 가용합니다. 값 조건은 R에서 !is.na(value) & value>=5처럼 참인 위치를 명시합니다. NA가 든 논리 벡터로 자료틀을 바로 부분선택하면 NA 행이 생길 수 있으므로, SQL WHERE와 같은 선택이라고 숨겨 부르지 않습니다.

Base R’s default merge can match NA keys, unlike an ordinary SQL equality join. For a single matching column, an explicit rule such as incomparables=NA can be relevant; do not generalize that option to every composite-key design.

Our fixed toy programs have available keys. R value filtering explicitly selects true positions with !is.na(value) & value>=5. Direct data-frame subsetting with an NA-containing logical vector can create NA rows, so it must not be silently described as SQL WHERE semantics.

기초Foundations

23. 없는 대응을 찾는 질문과 NULL값을 찾는 질문23. Absent matches and NULL values are different questions

가정 오른쪽에 A와B가 있고 C가 없을 때, “대응 키가 없는 왼쪽 행”은 C입니다. 키 조건을 만족하는 오른쪽 행이 존재하지 않는다는 NOT EXISTS 방식으로도 표현할 수 있습니다. 값이 NULL인 B는 존재 여부와 무관하게 원키가 있습니다.

NULL을 포함한 목록에 대한 NOT IN은 미지 논리 때문에 예상과 달라질 수 있습니다. 이 장은 모든 방언의 반대 조인 문법을 구현하지 않습니다. 원하는 관계를 먼저 존재·값 가용성·추가 조건으로 나누고, 실제 DB의 의미와 작은 반례를 확인하는 습관을 익힙니다.

If the right table has A and B but no C, the absent-match left record is C. This can be expressed by NOT EXISTS for the declared key condition. B exists even though its value is NULL.

A NOT IN list containing NULL can behave unexpectedly through unknown logic. This chapter does not implement every dialect’s anti-join syntax. First distinguish existence, value availability and extra predicates, then verify the database semantics with a small counterexample.

기초Foundations

24. 실습 C · 원키와 NULL 확장의 경로를 추적한다24. Lab C · trace original keys and NULL extension

ON·WHERE·IS NULL·잘못된 = NULL을 바꾸어 결과를 먼저 예측합니다. 원 오른쪽에는 A10,BNULL만 있고 C가 없다는 조건은 고정입니다. ON의 B는 원키가 있지만 조건에서 탈락한 행이라는 점을 확인하세요.

각 출력의 원키 존재 표지는 가정 원표에서 별도로 계산한 것입니다. 오른쪽 결과 키 NULL만 보고 역으로 추측한 값이 아닙니다. Python·SQLite 실제 출력과 SQL 의미를 명시적으로 맞춘 R 대응 출력을 구분해 비교합니다.

Predict the ON, WHERE, IS NULL and incorrect = NULL results. The original right table stays A10, BNULL with C absent. Under ON filtering, B has an original key but fails the value predicate.

Original-key presence is separately computed from the toy source, rather than inferred from a NULL output identifier. Compare native Python/SQLite output with the explicitly constructed R counterpart.

기초Foundations

25. COUNT(*)와 COUNT(X)의 분모를 나눈다25. Separate COUNT(*) from COUNT(X)

가정 A집단 값은 (0,2), B집단은 (NULL,4), C집단은 (NULL)입니다. 전체 원행은 5개이고 X가 가용한 행은 3개입니다. COUNT(*)는 행을 세고 COUNT(X)는 X가 NULL이 아닌 값을 셉니다. 관측 0도 값이므로 COUNT(X)에 들어갑니다.

LEFT 뒤 COUNT(*)에는 대응이 없어 추가된 NULL 확장 행도 포함됩니다. “오른쪽 기록 수”를 세려면 가용한 오른쪽 원키를 COUNT하는 등 질문에 맞는 표현이 필요합니다. 행·키·값의 수를 같은 수라고 가정하지 않습니다.

Toy group A contains (0,2), B contains (NULL,4), and C contains (NULL). There are five source rows and three available X values. COUNT(*) counts rows; COUNT(X) counts non-NULL X values. Observed zero counts as available.

After LEFT JOIN, COUNT(*) also counts NULL-extended rows. Counting actual right records instead requires an appropriate nonmissing right identifier. Row, key and value counts answer different questions.

기초Foundations

26. 합과 평균에 들어간 가용값을 밝힌다26. State which values enter SUM and AVG

A의 가용합 2·가용수 2이므로 AVG는 1이고, B는 가용합 4·가용수 1이므로 AVG는 4입니다. 이 수치형 계약의 SQLite AVG는 NULL을 제외한 평균입니다. B의 AVG를 모든 B행의 원 진실 평균이라고 바꾸어 해석하지 않습니다.

SQLite는 비수치 텍스트를 AVG에서 0처럼 해석할 수 있습니다. 그래서 SQL이 돌아갔다고 원 열의 수치형이 검증된 것은 아닙니다. 이번 실행은 보존한 수치 소수와 빈 칸을 명시적으로 REAL 또는 NULL로 변환한 뒤 사용합니다. 변환의 적합성은 입력 계약과 원문 대조로 따로 확인합니다.

A has available sum two and count two, giving AVG one. B has available sum four and count one, giving AVG four. Under the numerical-input contract, SQLite AVG excludes NULLs. That does not recover the unknown full B-group mean.

SQLite AVG can interpret nonnumeric text as zero. Successful execution therefore does not validate a numerical source column. These runs explicitly convert retained numerical decimals and blanks to REAL or NULL, with the conversion checked separately against the source contract.

기초Foundations

27. 모두 NULL인 그룹과 존재하지 않는 그룹27. An all-NULL group differs from an absent group

C는 원행이 한 개 있어 GROUP BY 결과에 나타나지만 COUNT(X)=0, SUM(X)=NULL, AVG(X)=NULL입니다. 합계 빈 집합을 수학에서 0으로 정의하는 관례와 SQLite SUM의 반환 계약을 혼동하지 않습니다. SQLite의 다른 함수 total도 같은 함수라고 부르지 않습니다.

반면 원표에 D행이 하나도 없으면 GROUP BY만으로 D그룹이 새로 나타나지 않습니다. 그룹 없이 전체를 집계하는 질의와 GROUP BY 질의도 빈 입력에서 출력 행 수가 다를 수 있습니다. C의 미관측, D의 행 부재, 관측 평균 0을 각기 구별하세요.

C has one original row and therefore appears in GROUP BY output, but COUNT(X)=0, SUM(X)=NULL and AVG(X)=NULL. Do not confuse SQLite SUM’s return contract with the mathematical convention of a zero empty sum or the distinct SQLite total function.

D has no original rows and is not generated merely by GROUP BY. An aggregate without GROUP BY also has a different empty-input output shape. Distinguish C’s unavailable values, D’s absent rows and an observed mean of zero.

기초Foundations

28. COALESCE는 결측의 진실을 복원하지 않는다28. COALESCE does not recover missing truth

AVG(COALESCE(X,0))을 사용하면 A는 1, B는 (0+4)/2=2, C는 0입니다. AVG(X)의 1,4,NULL과 다릅니다. NULL을 관측 0으로 가정한 계산이 새로 생긴 것이며, SQL 함수가 원래 미관측값을 알아낸 것은 아닙니다.

일부 질문에서 명시적 0 대체가 정의에 맞을 수는 있지만 근거와 대상을 먼저 선언해야 합니다. 이번 실제 임금·GDP 비교에서는 원자료를 복구한 방법으로 인정하지 않고 의도적으로 다른 가정 계산으로 표시합니다. 원자료의 NULL 상태는 그대로 남깁니다.

AVG(COALESCE(X,0)) gives A one, B two and C zero, rather than AVG(X)’s one, four and NULL. This substitutes assumed zeros; the function has not learned the unavailable source values.

An explicitly defined question can sometimes justify replacement, but its meaning and evidence must be declared first. The actual wage/GDP comparisons here label zero replacement as a different hypothetical calculation. Original NULLs remain preserved.

기초Foundations

29. GROUP BY와 HAVING의 질문을 나눈다29. Separate GROUP BY and HAVING questions

다음은 실제 가정 집계에 사용한 SQL입니다. GROUP BY는 A,B,C별로 요약을 만들고, 각 결과에 전체행·가용행·가용합·평균을 같이 둡니다. WHERE는 집계 전 입력 행 조건이고 HAVING은 집계 후 그룹 조건입니다. HAVING COUNT(X)>=2를 추가한 별도 실행은 A만 남깁니다.

SELECT g,COUNT(*) AS all_rows,COUNT(x) AS available_rows,SUM(x) AS available_sum,AVG(x) AS reported_mean FROM records GROUP BY g ORDER BY g;

그룹 키도 아닌 일반 열을 임의로 SELECT하면 어떤 값을 대표로 골랐는지 불명확할 수 있습니다. SQLite가 허용하는 bare-column 확장을 모든 SQL에서 의미 있는 그룹 대표값으로 일반화하지 않습니다. 필요한 열을 그룹 키 또는 명시한 집계로 표현합니다.

This SQL was used for the actual toy aggregate. GROUP BY produces A, B, C summaries with original counts, available counts, sums and means. WHERE filters input records; HAVING filters resulting groups. The separate run adding HAVING COUNT(X)>=2 retains only A.

SELECT g,COUNT(*) AS all_rows,COUNT(x) AS available_rows,SUM(x) AS available_sum,AVG(x) AS reported_mean FROM records GROUP BY g ORDER BY g;

An ungrouped, nonaggregated selected column can have an unclear representative value. Do not generalize SQLite’s bare-column extension into a portable or substantively justified group summary. Express required columns as group keys or specified aggregates.

심화Extension

30. 그룹 평균의 평균은 언제 전체 평균인가30. When does averaging group means recover the pooled mean?

가정 A평균 1은 가용 2개, B평균 4는 가용 1개에서 왔습니다. 둘의 균등 평균 2.5는 세 가용값의 전체 평균 2와 다릅니다. 원 가용값 균등을 원하면 그룹의 가용수를 가중치로 써야 합니다. C처럼 가용수 0·평균NULL인 그룹을 평균 0으로 바꾸어 끼워 넣지 않습니다.

xˉ=∑gngxˉg∑gng\bar x=\frac{\sum_g n_g\bar x_g}{\sum_g n_g}

식은 가용수가 양수인 그룹에 대해 쓰며 전체 가용수도 양수여야 합니다. 조인 증폭까지 있었다면 원래 관측 단위의 가중치가 이미 달라졌을 수 있습니다. 집계의 수학과 표적의 선택을 모두 확인하세요.

A’s mean one uses two values; B’s mean four uses one. Their equal-group mean 2.5 differs from the pooled available-value mean two. Weight by available group counts to recover equal original-value weighting. Do not insert a zero for an all-NULL group.

xˉ=∑gngxˉg∑gng\bar x=\frac{\sum_g n_g\bar x_g}{\sum_g n_g}

The expression uses positive-count groups and requires a positive total available count. Earlier join amplification may already have changed source-unit weights. Check both the aggregation identity and the intended target.

기초Foundations

31. 원행 분할과 조인 후 반복을 따로 검사한다31. Check source partitions separately from joined repetition

집단이 원행을 겹치지 않게 모두 나누면 집단 행 수 합은 전체 원행 수와 같습니다. 가용수 합도 전체 가용수와 같습니다. 그러나 같은 사람을 조인으로 여러 번 만든 뒤에는 합이 잘 맞더라도 원래 사람 균등 표적이 아닐 수 있습니다.

실제 교육집단 ≤12년과 >12년은 원 3,613행을 1,806행과 1,807행으로 나눕니다. 가용 로그는 각각 1,489개와 1,521개이고 미관측은 317개와 286개입니다. 1,489+1,521=3,010과 317+286=603을 함께 확인합니다. 교육집단 차이는 관측 요약이며 교육의 인과효과를 증명하지 않습니다.

If groups partition original records without overlap, their row counts sum to the original total, and their available counts sum to the available total. After duplicated join matches, a consistent partition of output rows may still represent the wrong original-person weights.

The actual ≤12 and >12 schooling groups contain 1,806 and 1,807 source rows. Available logs number 1,489 and 1,521; missing logs number 317 and 286. Verify both 3,010 available and 603 unavailable totals. These observational group summaries do not identify a causal effect of schooling.

기초Foundations

32. 실습 D · 전체행·가용행·보고 평균을 비교한다32. Lab D · compare source counts, availability and reported means

고정 가정 (A:0,2; B:NULL,4; C:NULL)에서 가용 평균·0 대체 비교·HAVING을 선택합니다. 관측 0이 남는지, 모두 NULL인 C가 어느 열에서 NULL인지, HAVING이 어느 그룹을 제외하는지 먼저 적으세요.

실제 Python·SQLite는 SQL 집계를 수행하고 base R은 같은 수치형 계약을 명시한 대응 계산을 합니다. R의 가용값이 빈 경우 SUM/AVG를 SQL 계약에 맞춰 NULL로 반환하도록 따로 작성했습니다. 언어의 기본 빈 합이 우연히 같다고 가정하지 않습니다.

For fixed toy groups A:(0,2), B:(NULL,4), C:(NULL), choose available means, zero replacement or HAVING. Predict retention of observed zero, C’s NULL columns and the groups removed by HAVING.

Python/SQLite runs native SQL aggregation; base R explicitly constructs the stated numerical counterpart. Its empty available SUM/AVG are deliberately returned as NULL to match the SQL contract. The languages’ default empty-sum conventions are not assumed identical.

기초Foundations

33. SQL·실행 언어·데이터베이스를 구별한다33. Distinguish SQL, its host language and the database

SQL은 표의 생성·조회 등을 표현하는 언어이고 SQLite는 그 SQL을 해석하는 데이터베이스 엔진입니다. 이번 Python 프로그램은 표준 모듈 sqlite3로 SQLite를 호출합니다. sqlite3.connect(":memory:")는 새 메모리 데이터베이스를 만들어 원 CSV나 외부 서버를 수정하지 않습니다.

Python 3.12.14와 이 실행에 연결된 SQLite 3.53.1의 버전을 함께 보관합니다. Python 버전이 같아도 연결된 SQLite 버전은 다를 수 있습니다. R 기록은 base R 4.5.1의 별도 대응 계산이며 SQL 실행 기록의 다른 이름이 아닙니다.

SQL expresses operations on tables; SQLite is a database engine interpreting a SQL dialect. The Python programs call it through the standard sqlite3 module. sqlite3.connect(":memory:") creates a new in-memory database rather than modifying source CSVs or an external server.

Both Python 3.12.14 and its linked SQLite 3.53.1 are archived. Equal Python versions do not necessarily imply equal SQLite versions. Base R 4.5.1 records are separate counterpart calculations, not another name for the native SQL execution route.

기초Foundations

34. 원 소수와 NULL을 명시적으로 적재한다34. Load source decimals and NULLs under an explicit schema

실제 SQL 프로그램은 UTF-8 CSV를 읽고 원 키·연도·값을 선언한 열에 넣습니다. 수치 문자열은 원 소수에 대한 분수로 해석한 뒤 SQLite REAL에 넣을 수로 변환하고, 빈 원값은 Python None을 통해 SQL NULL로 넣습니다. 원 CSV의 소수 문자열은 그대로 따로 보존됩니다.

테이블에 REAL이라고 적었다는 사실만으로 모든 원문 변환이 검증되는 것은 아닙니다. 잘못된 문자열·예상하지 않은 결측·중복 키는 적재 전후의 계약으로 확인해야 합니다. 이번 고정 실제 파일의 대조가 임의 파일을 읽는 완성형 수입기를 인증한 것은 아닙니다.

The actual SQL programs read UTF-8 CSVs and load declared key, year and value columns. Numerical source strings are interpreted as fractions before conversion to SQLite REAL; blank source values become Python None and then SQL NULL. Original decimal strings remain in separate source files.

A REAL declaration alone does not validate every conversion. Unexpected text, missingness and repeated keys require explicit input and load checks. Verification of these fixed files is not certification of a general importer for arbitrary files.

기초Foundations

35. 정확한 개수와 근사 평균의 지위를 나눈다35. Distinguish exact counts from numerical mean approximations

여기서 720·3,613·410 같은 작은 정수 행 수는 정확하게 비교합니다. 하지만 SQLite REAL은 원 소수의 무한 정밀 유리수 연산이 아닙니다. 합·평균의 마지막 자리는 binary64 반올림과 계산 순서에 영향을 받을 수 있습니다.

실제 점포 완전짝 384개의 원 소수 변화 평균은 정확히 −541/7680 FTE입니다. SQL AVG의 근사 표시는 약 −0.0704427083 FTE입니다. 이 둘을 대조하되 SQL의 인쇄 자릿수를 원측정의 정밀도나 정확 분수라고 부르지 않습니다. 분수 정확성도 원 소수 입력에 대한 산술 성질이지 측정 진실성 인증은 아닙니다.

Dˉ=−5417680 FTEDˉ≈−0.0704427083 FTE\begin{gathered}\bar D=-\frac{541}{7680}\text{ FTE}\\\bar D\approx-0.0704427083\text{ FTE}\end{gathered}

Small integer counts such as 720,3,613 and 410 are compared exactly here. SQLite REAL arithmetic, however, is not unlimited exact rational arithmetic on published decimals. Final sum/mean digits can reflect binary 64 rounding and accumulation order.

The mean of 384 complete source-row establishment changes is exactly −541/7680 FTE on the retained decimals. SQL AVG displays approximately −0.0704427083 FTE. Compare them without calling displayed digits an exact fraction or measurement precision. Exact arithmetic on source decimals is also distinct from certifying the measurements themselves.

Dˉ=−5417680 FTEDˉ≈−0.0704427083 FTE\begin{gathered}\bar D=-\frac{541}{7680}\text{ FTE}\\\bar D\approx-0.0704427083\text{ FTE}\end{gathered}
기초Foundations

36. 명시한 열·별칭·순서로 결과를 재현한다36. Reproduce results with explicit columns, aliases and order

SELECT *은 빠른 탐색에는 편리하지만 표에 열이 추가되면 출력 구조가 달라질 수 있습니다. 필요한 열과 별칭을 명시하면 원행 쌍·단위·집계 정의를 확인하기 쉽습니다. 두 표에 같은 이름의 열이 있을 때는 어느 쪽인지 별칭으로 적습니다.

ORDER BY 없는 결과의 물리적 행 순서를 정해진 계약처럼 읽지 않습니다. 정렬 열에 동률이 있으면 그 동률 안의 순서도 별도 키가 필요합니다. 이번 조합 조회는 양쪽 원행을 함께 정렬하여 표시 순서를 정합니다. 정렬은 원래 잘못된 키 대응을 고치는 작업이 아닙니다.

SELECT * is convenient for exploration but can change output shape when columns are added. Explicit columns and aliases clarify source pairs, units and aggregate definitions. Qualify same-named fields with their table aliases.

Without ORDER BY, physical output order is not a declared result contract. Ties in ordering fields need additional keys if tie order matters. The combination queries explicitly order both source positions. Sorting does not repair an invalid matching relationship.

기초Foundations

37. 값 바인딩과 식별자 선택을 구분한다37. Separate binding values from selecting identifiers

실제 키 예의 INSERT INTO records VALUES(?,?)는 SQL 문자열과 입력 값을 나눕니다. executemany에 원행 값 쌍을 주면 각 물음표에 값이 바인딩됩니다. 문자열 인용부호가 든 값도 SQL 구문의 일부로 덧붙이는 방식과 구별됩니다.

이 물음표는 테이블명이나 열 이름을 자동으로 대신하는 장치가 아닙니다. 실제 프로그램의 소수 테이블명은 코드 안에서 고정한 목록에서만 선택합니다. 새 분석에서는 값·식별자·SQL 구문을 분리하고 해당 드라이버의 계약을 확인하세요. 이번 화면은 입력 메모를 쿼리로 보내지 않습니다.

The actual key example uses INSERT INTO records VALUES(?,?), separating SQL text from data values. executemany binds each supplied row pair to those placeholders. A value containing a quote is data, rather than a fragment appended into SQL syntax.

A placeholder does not automatically substitute a table or column identifier. The few table names in the actual programs are selected only from fixed source-code lists. Keep values, identifiers and SQL syntax distinct under the driver’s contract. Prediction notes here are never sent as queries.

기초Foundations

38. 행 수가 맞아도 짝·분모·합을 더 확인한다38. Check pairs, denominators and totals beyond result size

조인 감사는 원행 수, 키별 대응 수, 미일치 키, 출력 원행 쌍, 값 가용수, 집계 단위를 함께 봅니다. 같은 3행이 나온 INNER 예처럼, 총개수만 맞아도 구성은 틀릴 수 있습니다. 고유성 통과도 분석 목적의 올바른 관계를 대신 증명하지 않습니다.

키별 LₖRₖ 예측과 실제 개수를 대조하고, 원행 키로 몇 개를 역추적합니다. 같은 소수합을 정확 분수와 SQL 근사로 별도 계산하면 산술 오류를 찾는 데 도움이 됩니다. 그렇다고 여러 계산의 일치가 대표성·독립성·인과관계까지 보장하지는 않습니다.

A join audit inspects source counts, matches per key, unmatched keys, output source pairs, value availability and aggregation units. As in the three-row INNER example, a correct total can hide an incorrect composition. Unique keys also do not establish that a substantive linkage is appropriate.

Compare multiplicity-based counts with actual results and trace selected source pairs back to the input. Independent exact-fraction and SQL-approximation sums help detect arithmetic errors. Agreement still does not establish representativeness, independence or causality.

기초Foundations

39. 보관 실행과 새 실행의 범위를 솔직히 적는다39. State archived execution and fresh-run scope honestly

이 장의 고정 프로그램은 키 8개·조인 12개·NULL 8개·집계 6개·실제 SQL 10개로 총 44개입니다. 키 반복·NULL 실패 4개도 원 오류 출력과 종료 상태를 보존합니다. 브라우저 버튼은 이 기록을 조회하며 데이터베이스 엔진을 새로 시작하지 않습니다.

코드·SQL·입력 파일 해시와 버전·R의 문자 환경 및 숫자 출력 옵션을 함께 보관합니다. 새 터미널에서는 내려받은 폴더 구조와 입력 경로를 유지하고 Python 또는 Rscript --vanilla로 실행합니다. 실제 파일·코드·환경이 다르면 같은 출력이라고 미리 가정하지 않습니다.

The chapter archives 44 fixed programs: eight key checks, twelve joins, eight NULL examples, six aggregations and ten actual-source SQL queries. Four key-check failures retain actual errors and exit status. Browser buttons retrieve these records rather than start a new database engine.

Archive code, SQL, input hashes, versions and R character/numeric-output settings. Fresh-terminal execution uses the downloaded folder layout and Python or Rscript --vanilla. Do not presume identical output when inputs, code or environment differ.

기초Foundations

40. 실습 E · 실제 열 개 SQL의 원문과 출력을 대조한다40. Lab E · compare ten actual-source SQL texts and outputs

국가 정상·고의 교차연도 조합, 사람의 full/available-only INNER/LEFT/WHERE 및 집단 집계, 점포 정상·고의 코드 조합과 407의 네 짝 중 하나를 고릅니다. 먼저 분모와 결과 개수를 예상한 뒤 실제 SQLite 출력을 공개하세요.

각 SQL은 새 Python 프로세스와 새 메모리 DB에서 실제 실행했습니다. 전체 드라이버·SQL·필요한 7개 원표 CSV를 내려받아 재실행할 수 있습니다. 의미상 잘못된 SQL도 실행은 성공할 수 있으며 화면은 그 결과를 새로운 관측이라고 부르지 않습니다.

Select a correct or invalid cross-year country query; full/available-only person INNER, LEFT, WHERE or grouped queries; or correct/invalid store joins and the four code-407 pairs. Predict denominators and counts before revealing native SQLite output.

Each query actually ran in a fresh Python process with a new in-memory database. Download its driver, SQL and seven required source-table CSVs to reproduce it. A substantively invalid query can execute successfully; its output is not automatically new observational data.

기초Foundations

41. 실제 국가년 · ISO와 연도 두 키를 보존한다41. Actual country-years · retain ISO and year together

보관한 World Bank의 GDP와 기간 기대수명 표는 각각 16국×45년=720행입니다. 같은 ISO·같은 연도로 붙이면 720개 원 국가년이 연결됩니다. GDP의 VNM 1980~1983 네 미관측은 조인했다고 채워지지 않습니다. 키 일치와 값 가용성은 다릅니다.

ISO만 사용한 32,400조합은 같은 국가의 다른 연도도 연결한 고의 오류입니다. 그 숫자를 더 큰 국가년 표본이라고 쓰지 않습니다. 원 API 행 위치·지표 코드·연도를 함께 보관하여 어느 원값이 연결됐는지 추적합니다. 기대수명은 기간지표이며 개인의 실제 수명 관측이 아닙니다.

The retained World Bank GDP and period-life-expectancy tables each contain 16×45=720 country-years. Matching ISO and year links those 720 source country-years. Four unavailable Vietnam GDP values in 1980–1983 remain unavailable; key matching does not fill values.

The 32,400 ISO-only combinations deliberately connect different years and are not a larger sample of country-year observations. Preserve original API positions, indicator codes and dates. Period life expectancy is a population statistic rather than an observed individual lifespan.

기초Foundations

42. 실제 사람 · 일치한 키의 NULL값과 없는 키를 나눈다42. Actual persons · distinguish matched NULLs from absent keys

원 인원 표 3,613행의 키를 모두 가진 full 오른쪽 로그 표는 값 NULL인 603개의 키도 포함합니다. INNER로 붙여도 3,613행이고 가용 로그는 3,010개입니다. 반면 available-only 오른쪽 표는 그 603개 키 자체를 담지 않아 INNER 결과가 3,010행입니다.

available-only에 LEFT를 하면 원 인원 3,613행을 남기지만 그 뒤 WHERE log_wage IS NOT NULL을 적용하면 3,010행으로 줄어듭니다. full의 matched NULL과 available-only의 absent key는 다른 표 설계입니다. 어느 경우도 새 임금이나 누락 원값을 복원한 것은 아닙니다.

The full right outcome table contains all 3,613 person keys, including 603 NULL log values. INNER JOIN therefore returns 3,613 rows with 3,010 available logs. The available-only right table omits those 603 keys, so its INNER result has 3,010 rows.

A LEFT join to the available-only table retains 3,613 people; subsequent WHERE log_wage IS NOT NULL reduces the result to 3,010. Full-table matched NULLs and available-only absent keys reflect different table designs. Neither recovers unavailable wages.

기초Foundations

43. 실제 점포 · 407의 네 조합에서 두 교차를 찾는다43. Actual establishments · find two crossed code-407 pairs

NJ/PA의 원 410행은 원행 번호로 전후를 붙이면 410행, 변화가 가용한 완전짝은 384개입니다. 원 코드 407은 원행 42와 168에서 반복됩니다. 두 행을 원코드로만 붙이면 (42,42),(42,168),(168,42),(168,168)의 네 조합이 됩니다.

같은 원행 짝의 변화는 각각 0과 2.5 FTE이고, 교차 조합 3.5와 −1 FTE는 실제 같은 점포의 전후 변화가 아닙니다. 전체 코드 조인은 412조합·완전값 386개가 되어 평균도 −491/7720으로 바뀝니다. 정상 짝 평균 −541/7680과 비교하여 원행 대응을 확인하세요. 이 관측 변화 자체로 정책효과가 식별되지는 않습니다.

Joining the 410 NJ/PA source rows by their original row key returns 410 pairs, of which 384 have available changes. Store code 407 repeats at source rows 42 and 168. Code-only matching creates four pairs: (42,42),(42,168),(168,42),(168,168).

The same-row changes are zero and 2.5 FTE. Crossed values 3.5 and −1 FTE are not observed changes of the same establishment. The full code-only join gives 412 combinations and 386 complete values, changing its mean to −491/7720 rather than −541/7680. These observational changes also do not identify a policy effect.

기초Foundations

44. 키 연결의 성공은 인과효과나 독립성을 증명하지 않는다44. Successful linkage proves neither causality nor independence

원행 키를 바르게 붙이는 것은 자료 구조의 필요 작업입니다. 그러나 같은 사람을 두 번 관측한 자료는 두 독립 사람의 표본과 다릅니다. 시점별 국가값도 시간의존이 있을 수 있으며, 국가·개인·점포의 관측 단위를 서로 섞지 않습니다.

전후 평균 차이를 정책효과라고 부르려면 비교 설계·반사실·교란 조건이 추가로 필요합니다. 이 장은 조인·분모·산술을 검증하며 그런 인과 조건이나 상위 모집단 대표성을 인증하지 않습니다. 바른 키와 바른 연구 질문은 연결되지만 같은 검사가 아닙니다.

Correct source-key linkage is necessary data work, but repeated observations of one person are not two independent people. Country values can be temporally dependent. Keep country, person and establishment units distinct.

Interpreting a before/after mean difference as a policy effect additionally needs a comparative design, counterfactuals and confounding assumptions. This chapter verifies linkage, denominators and arithmetic without certifying causal identification or population representativeness.

기초Foundations

45. 유일 키가 없어도 억지로 하나를 만들지 않는다45. Do not invent a unique relationship when evidence is absent

같은 이름·같은 코드·비슷한 값만으로 두 파일의 현실 개체가 같은지 결정되지 않을 수 있습니다. 임의로 첫 행만 고르거나 가까운 값을 붙이면 출력은 생기지만 근거가 새로 생긴 것은 아닙니다. 후보 대응과 미해결 상태를 보존하는 것이 필요할 수 있습니다.

선택 심화에서는 확률적 연결이나 오류 민감도를 다룰 수 있지만 이 장의 고정 등호 조인은 그런 모형을 구현하지 않습니다. 원 407의 두 기록을 “중복 입력”이라고 확정하여 하나를 지우지도 않습니다. 선언 키·파일 범위·관측 단위·알 수 없는 관계를 각각 적습니다.

Equal names, codes or similar values may not establish that records concern the same real entity. Taking the first row or closest value produces an output without new identifying evidence. Retain candidate matches and unresolved linkage status when needed.

Advanced probabilistic linkage and error sensitivity require additional models; the fixed equality joins here do not implement them. The two code-407 records are not declared accidental duplicates and deleted. State keys, archive scope, observation units and unresolved relationships separately.

기초Foundations

46. 실습 F · 실제 원행을 양쪽 표까지 추적한다46. Lab F · trace actual source rows to both input tables

국가 정상 국가년, 사람 원행, 점포 원행을 선택합니다. 국가는 두 API 원행 위치와 같은 연도, 사람은 full 키 존재·값 NULL·available-only 키 존재, 점포는 정상 원행 짝과 코드만 썼을 때의 추가 대응을 확인합니다.

표시 번호는 이번 보관본의 원행 추적 번호입니다. 원래 개체의 영구 ID나 난수 추출 번호로 바꿔 해석하지 않습니다. 원자료를 수정하거나 새 조합을 원관측으로 추가하지 않습니다.

Select an actual country-year, person source row or establishment source row. Inspect both API positions and matching years; full-key existence, NULL value and available-only key existence; or a correct store pair versus code-only alternatives.

Displayed numbers trace this retained archive. They are neither automatically permanent entity IDs nor random-sampling indices. No source record is modified or invalid combination promoted to an original observation.

기초Foundations

47. 세 실제 사례를 키·값·분모로 다시 읽는다47. Revisit three actual cases through keys, values and denominators

국가 사례 · 두 표의 같은 국가는 같은 연도까지 뜻하지 않는다

World Bank의 선택 16국·1980~2024년 실제 720개 국가년에서 GDPpc와 출생 시 기대수명을 서로 다른 표로 나눕니다. GDP 단위는 2015년 불변 USD/인이고 기대수명은 해당 시점 사망률 패턴을 반영한 집단 지표의 연수입니다. 기대수명은 특정 개인의 수명 예측이 아닙니다. 각 표의 고유 키는 (ISO, 연도)이며 두 지표의 원 API 행 위치와 원 소수를 보존합니다.

SELECT COUNT(*) AS joined_rows FROM gdp g JOIN life l ON g.iso=l.iso AND g.year=l.year;

같은 국가·같은 연도로 조인하면 720행입니다. 국가 코드만 맞추면 국가마다 GDP 45년×기대수명 45년이 연결돼 16×45×45=32,400조합이 됩니다. 그 안에는 한국의 1980년 GDP와 2024년 기대수명처럼 서로 다른 시점도 섞입니다. SQL이 오류 없이 실행됐다는 사실은 그 조합이 실제 같은 해의 관측이라는 증거가 아닙니다. 이번 수치는 실제 입력을 메모리 SQLite에 넣어 실행하고 별도 정확한 키 개수 계산으로 확인했습니다.

실제 두 표에서 실행한 조인 · 잘못된 조합은 새 관측이 아님
조인 조건GDP 행기대수명 행출력 행
ISO+같은 연도720720720
고의로 잘못된 ISO만72072032400
먼저 생각한 뒤 풀이 보기: 조인 결과의 GDP 평균이 예상과 같으면 키가 맞다고 봐도 되나요?

아닙니다. 각 GDP가 같은 횟수만큼 반복되면 평균이 유지될 수도 있습니다. 평균 하나보다 키의 유일성·행 수·연도 대응·결측 분모를 함께 검사해야 합니다. 두 지표가 잘 연결돼도 국가 간 관측 상관이 개인 수준 인과효과로 바뀌지는 않습니다.

사람 사례 · 키가 없는 것과 값이 NULL인 것은 다르다

Card 실제 원행 3,613명의 교육 기록을 왼쪽 표에 둡니다. 오른쪽 outcome 표를 두 가지로 만듭니다. 첫 표는 원행 키 3,613개를 모두 담고 원자료 극단값 정리 로그 임금 603개를 NULL로 남깁니다. 두 번째는 로그가 가용한 3,010행만 담습니다. 변수는 1976년 시간당 임금(센트)의 로그이며 원행 키는 보관 파일 위치의 추적키입니다. 새로운 사람 식별·통계적 독립성을 보증하지 않습니다.

INNER JOIN은 키를 맞출 뿐, 맞은 행의 NULL 값을 자동 삭제하지 않습니다. 첫 오른쪽 표와 inner join하면 3,613행이고 두 번째 표와 inner join하면 3,010행입니다. 두 번째 표에 LEFT JOIN하면 원 3,613행을 보존하면서 미일치 키의 오른쪽 칸을 NULL로 만듭니다. 그 뒤 WHERE log_wage IS NOT NULL을 붙이면 다시 3,010행만 남습니다. 무엇이 원자료 결측이고 무엇이 표에서 제외한 키인지 구별해야 합니다.

실제로 실행한 네 조회 · COUNT(value)는 NULL 제외
오른쪽 표·규칙오른쪽 행결과 행가용 로그
전체 3,613키+NULL603 · INNER361336133010
가용 3,010키만 · INNER301030103010
가용 3,010키만 · LEFT301036133010
LEFT 뒤 WHERE 값 IS NOT NULL301030103010
SELECT p.school_group,COUNT(*) AS all_rows,COUNT(w.log_wage) AS available_logs,AVG(w.log_wage) AS available_mean,AVG(COALESCE(w.log_wage,0)) AS invalid_zero_mean FROM people p LEFT JOIN outcome_full w ON p.source_row_id=w.source_row_id GROUP BY p.school_group ORDER BY p.school_group;
실제 교육 집단의 집계 · 평균은 반올림, 인과 비교 아님
교육 기록COUNT(*)COUNT(log)원 결측가용 로그 평균
12년 이하180614893176.163655006
12년 초과180715212866.357943306
먼저 생각한 뒤 풀이 보기: COUNT(*)와 COUNT(log_wage)는 왜 다른가요?

COUNT(*)는 조인 결과 행을 세고 COUNT(log_wage)는 그중 값이 NULL이 아닌 행만 셉니다. AVG(log_wage)도 NULL을 분모에서 제외합니다. 결측을 0으로 바꾸는 COALESCE를 넣으면 원래 없던 로그 0, 즉 시간당 1센트라는 값을 만들어 다른 평균을 계산합니다. 숫자 변환·NULL 처리 규칙도 사전에 명시하세요.

점포 사례 · 같은 코드 조인이 410행을 412조합으로 늘린다

NJ/PA 원 410행을 전 시점·후 시점 표로 나누고 원행 키로 다시 연결하면 같은 원행의 짝 410개가 복원됩니다. 전후 FTE가 모두 가용한 것은 384개이며 불완전한 26행도 삭제하지 않습니다. FTE는 FT+0.5PT+관리자 수이고 구성 값 하나라도 없으면 해당 시점 FTE를 NULL로 남깁니다. 원 store 코드407은 서로 다른 원행42·168에 있어 코드 자체는 고유 키가 아닙니다.

SELECT COUNT(*) AS joined_rows,COUNT(a.after_FTE-b.before_FTE) AS complete_values,AVG(a.after_FTE-b.before_FTE) AS mean_difference FROM before_wave b JOIN after_wave a ON b.source_row_id=a.source_row_id;

코드만 조인하면 407의 두 전 행×두 후 행이 네 조합으로 늘어 전체 412행이 됩니다. 새로 생긴 교차 두 조합은 실제 점포의 변화가 아닙니다. 잘못된 조회는 결측이 없는 386조합의 평균을 계산하며 올바른 384짝 평균과 다릅니다. 이를 통계적으로 더 많은 표본을 얻었다고 해석하지 않습니다. 올바른 관측 변화도 정책의 인과효과라는 뜻은 아닙니다.

407 코드의 네 연결 · 같은 원행일 때만 정상짝
전 원행후 원행산술 변화 FTE같은 원행
42420예
421687/2아니오 · 무효 조합
16842-1아니오 · 무효 조합
1681685/2예
정상 조인과 고의 오류 조회 · 소수 반올림
규칙출력 행완전한 값 조합평균 변화 FTE
원행 키410384-0.070442708
고의 오류: 원 코드만412386-0.063601036
먼저 생각한 뒤 풀이 보기: DISTINCT를 붙이면 잘못된 412행이 정상 410행으로 자동 복구되나요?

아닙니다. DISTINCT는 선택한 출력 열의 값 조합을 구별할 뿐 현실의 올바른 짝을 알아내지 않습니다. 원행 키를 선택하면 잘못된 교차 조합도 서로 다르고, 키를 빼면 정상적으로 다른 기록까지 합쳐질 수 있습니다. 조인 전 키의 유일성과 기대 관계를 검사하고 조인 후 미일치·다중 일치·행 수·대표 짝을 확인하세요.

Country case · Matching countries does not match their years

Split the actual 720 country-year records for sixteen selected World Bank countries, 1980–2024, into GDPpc and period-life-expectancy tables. GDPpc uses constant-2015 USD/person; period life expectancy is a population indicator in years under contemporaneous mortality patterns, not a prediction of an individual lifespan. Each table’s unique key is (ISO, year). Preserve both indicators’ archived API positions and decimal strings.

SELECT COUNT(*) AS joined_rows FROM gdp g JOIN life l ON g.iso=l.iso AND g.year=l.year;

A same-country/same-year join returns 720 rows. Country-only matching combines 45 GDP years with 45 life-expectancy years per country: 16×45×45=32,400 combinations, including different periods. Successful SQL execution does not turn cross-year combinations into same-year observations. These counts come from actual in-memory SQLite execution and separate exact key-count calculations.

Executed joins on actual tables · invalid combinations are not new observations
Join conditionGDP rowsLife rowsOutput rows
ISO and same year720720720
Deliberately invalid ISO only72072032400
Think first, then reveal: Does an expected GDP mean prove that the join key is correct?

No. Repeating each GDP value equally can preserve a mean. Check uniqueness, row counts, year correspondence and valid denominators. Correct linkage also does not identify individual-level causal effects from country associations.

Person case · An absent key differs from a matched NULL value

Put all 3,613 actual Card education records in the left table. Build two right-side outcome tables: one retains all 3,613 keys with 603 NULL source-trimmed log wages; the other includes only the 3,010 available-log records. The variable is the source-trimmed log of 1976 hourly wages in cents/hour. Source-row keys trace archived positions, not guaranteed permanent identities or independent observations.

INNER JOIN matches keys; it does not automatically delete a matched NULL outcome. Joining the full right table returns 3,613 rows; joining the available-only table returns 3,010. LEFT JOIN to the latter retains all 3,613 left records and fills unmatched right fields with NULL. Adding WHERE log_wage IS NOT NULL afterwards retains 3,010. Separate original missing values from keys deliberately excluded from a table.

Four actually executed queries · COUNT(value) excludes NULL
Right-table design/ruleRight rowsOutput rowsAvailable logs
Full 3,613 keys+603 NULL · INNER361336133010
Available-only 3,010 keys · INNER301030103010
Available-only 3,010 keys · LEFT301036133010
LEFT then WHERE value IS NOT NULL301030103010
SELECT p.school_group,COUNT(*) AS all_rows,COUNT(w.log_wage) AS available_logs,AVG(w.log_wage) AS available_mean,AVG(COALESCE(w.log_wage,0)) AS invalid_zero_mean FROM people p LEFT JOIN outcome_full w ON p.source_row_id=w.source_row_id GROUP BY p.school_group ORDER BY p.school_group;
Actual schooling-group aggregation · rounded means, not causal effects
Recorded schoolingCOUNT(*)COUNT(log)UnavailableAvailable-log mean
At most 12 years180614893176.163655006
More than 12 years180715212866.357943306
Think first, then reveal: Why do COUNT(*) and COUNT(log_wage) differ?

COUNT(*) counts joined rows; COUNT(log_wage) counts non-NULL values. AVG also excludes NULL. COALESCE to zero invents log wage zero, meaning one cent/hour, and changes the average. Specify numeric conversion and NULL contracts explicitly.

Establishment case · A repeated-code join turns 410 rows into 412 combinations

Split the original 410 NJ/PA records into before/after tables and rejoin by source-row key to recover 410 same-record pairs. Both FTE values are available for 384; preserve the other 26 records. FTE equals full-time staff plus half part-time staff plus managers, with NULL if any required component is unavailable. Original store code 407 occurs at different source rows 42/168, so that code is not unique.

SELECT COUNT(*) AS joined_rows,COUNT(a.after_FTE-b.before_FTE) AS complete_values,AVG(a.after_FTE-b.before_FTE) AS mean_difference FROM before_wave b JOIN after_wave a ON b.source_row_id=a.source_row_id;

Joining only on code creates four combinations from the two code 407 before rows and two code 407 after rows, producing 412 output rows. The two crossed combinations are not actual establishment changes. The invalid query averages 386 complete combinations rather than 384 valid pairs. It has not created more independent observations. Even valid observed changes do not identify a causal policy effect.

Four code 407 combinations · only same-source-row links are valid
Before rowAfter rowArithmetic difference FTESame source row
42420Yes
421687/2No · invalid combination
16842-1No · invalid combination
1681685/2Yes
Valid join versus deliberate error · rounded means
RuleOutput rowsComplete value combinationsMean difference FTE
Source-row key410384-0.070442708
Deliberately invalid code only412386-0.063601036
Think first, then reveal: Does adding DISTINCT automatically repair 412 invalid rows into 410 valid rows?

No. DISTINCT compares selected output values, not real pairing identities. With source keys, crossed combinations remain distinct; without keys, different valid records may collapse. Check unique keys and expected relationships before joining, then unmatched/multiple matches, row counts and concrete pairs afterwards.

기초Foundations

48. 공식 문서와 다음 탐색 장으로 연결한다48. Connect official documentation to the next exploration chapter

SQLite SELECT 문서의 FROM·WHERE·GROUP BY/HAVING·ORDER BY 설명을 읽습니다. 개념 단계와 실제 최적화 순서를 같다고 가정하지 않습니다. 집계 문서는 COUNT·AVG·SUM의 NULL·빈 입력 계약에 한정합니다.

Python 3.12 sqlite3의 메모리 연결·execute/executemany·값 바인딩을 내려받은 실제 코드와 비교합니다. 온라인 문서의 세부 패치 버전과 보관 실행 버전도 구별합니다. R merge 문서에서는 다중 대응·NA·sort=FALSE의 순서 계약을 확인합니다.

다음 탐색 장에서도 조인 후 표적·단위·가용분모를 유지한 상태로 그림과 표를 만듭니다. 선택 심화는 관계대수·함수 종속·연결 오류·질의 최적화로 이어지지만, 이번 작은 실행을 그 모든 영역의 구현이나 증명이라고 부르지 않습니다.

Python · R · 원자료·단위·가공·출처

Read FROM, WHERE, GROUP BY/HAVING and ORDER BY in SQLite SELECT documentation. Distinguish conceptual steps from physical optimization. Restrict the aggregate reading to COUNT, AVG and SUM contracts for NULLs and empty inputs.

Compare memory connections, execute/executemany and value binding in Python 3.12 sqlite3 documentation with the downloaded programs. Online documentation patch versions and archived runtime versions are distinct. Check multiple matches, NA handling and unspecified sort=FALSE order in R’s merge documentation.

The next exploration chapter keeps join targets, units and available denominators attached to plots and tables. Further bridges lead to relational algebra, functional dependencies, linkage error and query optimization; these small executions do not implement or prove every such topic.

Python · R · Inputs, units, transformations and sources

Python·R 코드 실행 방법Run the Python/R companions

자료 묶음을 풀고 코드와 실제데이터 폴더를 함께 두세요. 터미널에서 코드 파일이 있는 폴더로 이동해 아래 명령을 실행합니다. 코딩이 처음이라면 손계산과 웹 실습을 먼저 하고, 데이터 사이언스 입문에서 코드를 배운 뒤 돌아와도 됩니다.Extract the bundle, keeping the scripts beside the data folder. In a terminal, enter the script folder and run the commands below. Beginners can complete hand calculations and browser labs first, returning to code after studying introductory data science.

python data06-reproduce.py
Rscript --vanilla --encoding=UTF-8 data06-reproduce.R

결과 파일은 각 코드에 지정된 결과 폴더에 저장됩니다. CSV 원자료는 덮어쓰지 않습니다.Result files are saved in the result directory specified by each script; the input CSVs are not overwritten.

영상·학자·함께 읽기Videos, thinkers and guided reading

본문의 질문을 넓히는 선택 학습입니다. 영상을 보기 전 질문을 먼저 읽고, 자신의 답을 쓴 뒤 해설과 비교하세요. 자료의 언어·선수 지식은 각 항목에 표시했습니다.Optional extensions to the chapter. Read the question first, write your answer, then compare with the explanation. Language and prerequisites are indicated below.

Harvard CS50 · 표 사이의 관계와 조인Harvard CS50 · Relations and joins

CS50 SQL · Lecture 1 Relating

키·일대다 관계·JOIN·GROUP BY를 본문의 실제 국가·사람·점포 키와 연결합니다. 정렬 위치로 관계를 추정하지 말고 원 단위·기대 일치 수를 먼저 적어 보세요.Connect keys, one-to-many relationships, JOIN and GROUP BY to the actual country/person/establishment keys. State units and expected match counts before relying on row positions.

교재 안의 YouTube 플레이어에서 재생합니다. 원영상에서 제공하는 자막은 플레이어의 CC·설정에서 선택할 수 있습니다.Playback stays in this chapter’s YouTube player. Available captions can be selected through CC/settings.

보고 읽은 뒤 답하기Respond after watching/reading 행이 같은 순서라는 사실이 관계를 보증하나요?Does equal row order establish a relationship?

생각을 점검하는 해설Check your reasoning

아닙니다. 유효한 키와 관계 제약으로 연결하고 미일치·다중 일치를 검사합니다.No. Join on valid keys/relationship constraints and inspect unmatched/multiple matches.

에드거 커드 · 물리 위치보다 관계로 자료 읽기Edgar Codd · Read relations rather than physical positions

IBM official history · relational model

1970년 관계 모형의 배경을 읽고, 원행 추적키와 현실 개체의 관계를 구분합니다. 고유 키 선언이 모든 원 코드를 저절로 고유하게 만들지는 않습니다.Read the relational-model history and distinguish source traces from real-world relationships. Declaring a key does not make every source code inherently unique.

공식 자료 읽기 ↗Read official resource ↗

보고 읽은 뒤 답하기Respond after watching/reading 숫자로 된 store 코드면 PRIMARY KEY로 쓰면 되나요?May any numeric store code serve as a primary key?

생각을 점검하는 해설Check your reasoning

아닙니다. 실제 유일성·NULL·변경 의미를 확인해야 하며 원407은 두 기록에서 반복됩니다.No. Check actual uniqueness, NULLs and meaning; original code 407 repeats in two records.

SQLite 공식 · ON·LEFT JOIN·WHERE의 순서Official SQLite · ON, LEFT JOIN and WHERE

SQLite SELECT · FROM and WHERE sections

ON으로 고른 조합과 외부 조인의 NULL 추가, 그 뒤 WHERE가 행을 제거하는 설명을 읽습니다. SQLite의 bare column 집계를 이식 가능한 SQL 규칙으로 일반화하지 않습니다.Read ON filtering, unmatched NULL rows in outer joins and later WHERE exclusion. Do not generalize SQLite bare aggregate-column extensions as portable SQL.

공식 자료 읽기 ↗Read official resource ↗

보고 읽은 뒤 답하기Respond after watching/reading 오른쪽 값 조건을 ON에서 WHERE로 옮겨도 LEFT 결과는 항상 같나요?Does moving a right-value condition from ON to WHERE always preserve LEFT JOIN results?

생각을 점검하는 해설Check your reasoning

아닙니다. WHERE의 조건이 NULL 행을 제외하면 왼쪽 기록을 보존하던 결과가 줄어들 수 있습니다.No. A WHERE predicate can discard NULL-extended rows and reduce the preserved left records.

SQLite 공식 · COUNT(*)·COUNT(X)·AVG(X)Official SQLite · COUNT(*), COUNT(X) and AVG(X)

SQLite built-in aggregates · avg/count only

COUNT(*)는 행, COUNT(X)는 NULL 아닌 값, AVG(X)는 가용 값 평균이라는 정의를 읽습니다. AVG가 비수치 텍스트를 0으로 처리할 수 있다는 주의도 확인하고 수치형 입력 계약을 먼저 검사하세요.Read row counts, non-NULL counts and available-value averages. Note that AVG can interpret nonnumeric text as zero, making a numeric-input contract necessary.

공식 자료 읽기 ↗Read official resource ↗

보고 읽은 뒤 답하기Respond after watching/reading SQL의 AVG가 실행됐으면 원 열이 수치라는 뜻인가요?Does successful AVG execution prove numeric source values?

생각을 점검하는 해설Check your reasoning

아닙니다. 먼저 수치 변환·실패·NULL 규칙과 유효 분모를 검사해야 합니다.No. Check conversion failures, NULL contracts and valid denominators first.

연습문제 · 계산에서 설명과 증명까지Exercises: calculation, explanation and proof

먼저 혼자 풀고 풀이를 여세요. 숫자와 함께 단위·포함 기준·계산 이유를 확인하세요.Attempt each problem before opening its solution. Check units, inclusion rules and the reason for the calculation.

1. 한 행의 단위The unit of a row

가정 GDP 표의 한 행은 국가·연도이고 가격표의 한 행은 국가·월입니다. 국가 코드만으로 붙인 뒤 “같은 시점의 두 값”이라고 할 수 있나요?

A toy GDP table uses country-years and a price table uses country-months. Does joining country codes establish a same-date comparison?

풀이와 확인할 이유Solution and explanation

아닙니다. 연도와 월의 대응 규칙이 필요합니다. 월을 어떤 연도·가중 방식으로 요약할지 또는 어떤 월을 선택할지 정하고, 출력의 단위와 기간을 명시한 뒤 키를 설계합니다. 국가 코드 일치만으로 시간 대응을 증명하지 않습니다.

No. Define how months correspond to years, including any selected month or aggregation weights. State the output unit and time coverage before choosing keys. Matching country alone establishes no time alignment.

2. 복합키의 유일성Composite uniqueness

가정 행 (A,2023),(A,2024),(B,2023)에서 국가 단독, 연도 단독, 국가·연도 쌍 중 어떤 것이 고유한가요?

For toy rows (A,2023),(A,2024),(B,2023), which of country, year and their pair is unique?

풀이와 확인할 이유Solution and explanation

국가 A와 연도 2023은 각각 반복되어 단독으로 고유하지 않습니다. 세 쌍은 모두 다르므로 이 표에서 국가·연도 쌍은 고유합니다. 다만 다른 파일·버전이나 NULL 포함 여부까지 자동 검증한 것은 아닙니다.

Only the pair is unique here. Country A and year 2023 each repeat. This conclusion concerns this table; other versions, files and missing-key contracts require their own checks.

3. 이어 붙인 문자열 키Concatenated identifiers

가정 두 키 쌍 (AB,C),(A,BC)를 구분자 없이 이어 붙였습니다. 둘 다 ABC가 됩니다. 원 쌍은 고유한데 문자열 키가 고유하지 않은 이유와 대안을 설명하세요.

Toy pairs (AB, C),(A, BC) both become ABC when concatenated without separators. Why is uniqueness lost, and what should be used?

풀이와 확인할 이유Solution and explanation

단순 이어 붙이기가 서로 다른 쌍을 같은 문자열에 대응시키기 때문입니다. 구조 있는 튜플 또는 두 열의 복합 제약으로 비교합니다. 구분자를 쓰는 경우에도 원값에 구분자가 들어갈 수 있는지와 이스케이프 규칙을 확인해야 합니다.

Concatenation maps distinct pairs to one string. Compare structured tuples or a composite column constraint. Even delimiter-based encoding needs an escaping rule if source values can contain the delimiter.

4. 키 NULL과 값 NULLA NULL key versus a NULL value

가정 기록 (id=A,score=NULL),(id=NULL,score=10)에서 id가 가용하고 고유해야 한다는 계약을 검사합니다. 어느 행이 키 계약을 실패하고 어느 행의 점수가 미관측인가요?

Toy records are (id=A, score=NULL),(id=NULL, score=10). The declared id contract requires available unique keys. Classify the two rows.

풀이와 확인할 이유Solution and explanation

두 번째 행은 id 가용성 계약을 실패합니다. 첫 번째 행은 id=A가 있고 score만 미관측입니다. 값 NULL을 키 부재로 바꾸거나 점수 10이 있다는 이유로 NULL키를 통과시키지 않습니다.

The second row fails key availability. The first has key A and an unavailable score. A NULL score does not remove its key; an available score does not validate a NULL identifier.

5. 제약 성공과 현실 정체A passed constraint and real identity

가정 id가 a,b,c로 고유하여 기본키 검사를 통과했습니다. 이것만으로 세 행이 서로 다른 실제 사람이며 독립 표본이라고 증명되나요?

Toy ids a, b, c pass a primary-key check. Does that establish three different actual people and independent sampling?

풀이와 확인할 이유Solution and explanation

아닙니다. 파일 안의 선언한 키 조건만 확인했습니다. 한 사람의 여러 관측에 서로 다른 원행 번호를 붙일 수도 있고, 서로 다른 사람끼리도 통계적으로 의존할 수 있습니다. 원 단위·관계·표집 설계는 별도 근거가 필요합니다.

No. It establishes only the declared file-level key condition. Repeated observations of one person can have different source-row keys, and different people can be dependent. Units, relationships and sampling need separate evidence.

6. 두 열이면 모두 통과하는가Do two columns always fix uniqueness?

가정 행 (A,2023),(A,2023)을 국가·연도 복합키로 선언했습니다. 두 열을 썼으니 유일성 문제가 해결되나요?

Toy rows (A,2023),(A,2023) receive a country-year composite key. Is the problem solved?

풀이와 확인할 이유Solution and explanation

아닙니다. 같은 쌍이 두 번 있어 복합키도 고유하지 않습니다. 열 개수가 아니라 선언한 속성 집합이 실제 원행을 구별하는지 확인해야 합니다. 임의의 순번을 붙이면 보관 행은 구별되지만 중복된 관계의 실질 문제를 자동 해결하지는 않습니다.

No. The same pair repeats. Uniqueness depends on actual values, not merely the number of columns. An extra row number distinguishes archive positions without automatically resolving the substantive repeated relationship.

7. 실제 키 실패의 지위Interpreting actual key failures

보관한 키 예에서 Python·SQLite는 반복 A에 IntegrityError를 내고 R은 stop으로 실패합니다. 둘 중 R도 SQLite를 실행했다고 써야 하나요?

An archived Python/SQLite repeated-A example raises IntegrityError; its R counterpart fails with stop. Did both run SQLite?

풀이와 확인할 이유Solution and explanation

아닙니다. Python은 SQLite 제약을 실제 실행했고 R은 명시한 base R 조건을 검사했습니다. 두 실패가 선언 계약의 대응 예라는 점은 비교할 수 있지만 실행 엔진을 같은 것으로 바꾸어 쓰지 않습니다. 실제 오류·종료 상태를 남깁니다.

No. Python actually invoked SQLite constraints; R evaluated explicit base-R conditions. Their declared-contract outcomes can be compared without misidentifying execution engines. Preserve actual errors and exit status.

8. 조인과 외래키 검사A join and a foreign-key check

가정 오른쪽에는 A만 있고 왼쪽에는 A,B가 있습니다. LEFT JOIN을 실행해 B의 오른쪽 칸이 NULL이 되었습니다. 프로그램이 B의 외래키 제약을 강제했다고 말해도 되나요?

A toy right table has A; the left has A, B. LEFT JOIN produces NULL right cells for B. Was a foreign-key constraint enforced?

풀이와 확인할 이유Solution and explanation

아닙니다. 조인 질의가 미일치 행을 표시한 것과 외래키 제약을 선언·활성화해 적재를 거부하는 것은 다릅니다. 이번 결과는 B가 조인 조건에서 미일치임을 보여 줍니다. 실제 제약의 존재와 강제 여부는 별도 확인합니다.

No. Showing an unmatched row differs from declaring and enforcing a foreign-key constraint that rejects a write. The query shows nonmatching B under its condition. Constraint declaration and enforcement require separate evidence.

9. 원순서와 관계Order and relationships

같은 학생들을 담은 두 가정 표 중 한 표를 점수순으로 정렬했습니다. 행 수가 같으므로 위치끼리 붙여도 되나요?

One of two toy student tables is sorted by score. Equal row counts remain. May positions be joined?

풀이와 확인할 이유Solution and explanation

안 됩니다. 정렬이 위치의 대응을 바꿨을 수 있습니다. 원 학생 키와 원행을 함께 유지하고 키로 연결한 뒤 미일치·다중 일치를 검사합니다. 같은 행 수는 같은 순서나 올바른 짝을 보증하지 않습니다.

No. Sorting can change positional correspondence. Retain source keys with whole records, join on declared keys and inspect unmatched or multiple matches. Equal counts prove neither equal order nor correct pairs.

10. 0인 값은 가용한가Is zero available?

가정 (id=A,value=0),(id=B,value=NULL)에서 value가 가용한 행 수를 세세요. 값이 참처럼 보이는지로 선택하면 어떤 문제가 생기나요?

Toy rows are (id=A, value=0),(id=B, value=NULL). Count available values and explain a truthiness filter.

풀이와 확인할 이유Solution and explanation

가용값은 A의 0 하나이므로 1개입니다. 값의 truthiness로 선택하면 관측 0까지 없앨 수 있습니다. NULL 여부와 숫자 0 여부를 분리하고, 키의 가용성도 value의 가용성과 별도로 검사합니다.

One value is available: the observed zero. A truthiness filter can wrongly remove that observation. Test NULL availability separately from numerical zero and separately from key availability.

11. INNER 짝을 손으로 세기Count INNER pairs by hand

가정 왼쪽 원행은 1:A,2:B,3:C이고 오른쪽 원행은 1:A값 10,2:A값 30,3:B값 20입니다. 키 등호 INNER의 원행 짝과 행 수를 구하세요.

Toy left rows are 1: A,2: B,3: C; right rows are 1: A10,2: A30,3: B20. List equality-INNER source pairs and their count.

풀이와 확인할 이유Solution and explanation

원행 짝은 (왼 1,오른 1),(왼 1,오른 2),(왼 2,오른 3)이고 3행입니다. 왼쪽 A가 두 번 기여하며 C는 사라집니다. 출력 3행과 왼쪽 3행이 같아도 구성이 보존된 것은 아닙니다.

The pairs are (left 1, right 1),(left 1, right 2),(left 2, right 3): three rows. A contributes twice and C disappears. Equality of output and left counts does not establish equal composition.

12. LEFT의 한 행 추가The extra LEFT row

왼쪽 1:A,2:B,3:C와 오른쪽 1:A10,2:A30,3:B20의 가정 키 등호 LEFT 결과는 몇 행인가요? C의 오른쪽 원행과 값을 어떻게 표시하나요?

For toy left 1: A,2: B,3: C and right 1: A10,2: A30,3: B20, count equality-LEFT rows and classify C.

풀이와 확인할 이유Solution and explanation

세 일치 짝에 C의 NULL 확장 한 행을 더해 4행입니다. C의 오른쪽 원행·값은 NULL입니다. A가 두 번 나오므로 모든 왼쪽 행을 정확히 한 번 남긴 결과는 아닙니다.

Three matches plus one NULL-extended C row give four. C’s right source position and value are NULL. A still appears twice, so preservation does not mean exactly one output per left record.

13. 다대다 조합Many-to-many combinations

비결측 키 등호 가정에서 왼쪽 A는 2행·B는 1행이고 오른쪽 A는 3행·B는 2행입니다. INNER 결과 행 수와 A의 기여를 구하세요.

With nonmissing equality keys, left multiplicities are A:2, B:1 and right multiplicities A:3, B:2. Count INNER rows.

풀이와 확인할 이유Solution and explanation

A는 2×3=6행, B는 1×2=2행이라 총 8행입니다. 각 행은 두 원행의 대응 쌍이며, 원래 독립 관측 8개를 새로 수집했다는 뜻은 아닙니다.

A contributes six and B two, giving eight. Each is a source-record pair, not evidence that eight new independent observations were collected.

14. 개수가 같아도 구성은 다르다Equal counts can hide different composition

가정 왼쪽 A,B,C 세 행을 오른쪽 A,A,B와 INNER 조인하면 3행입니다. 행 수가 보존됐으니 원 왼쪽 모두가 한 번씩 남았다는 주장을 반박하세요.

Toy left A, B, C joins right A, A, B by INNER to produce three rows. Refute preservation of each left row once.

풀이와 확인할 이유Solution and explanation

A가 두 번, B가 한 번 나오고 C는 없습니다. A의 한 추가 대응과 C의 소실이 개수에서 상쇄됩니다. 원행별 대응 수와 미일치 목록을 함께 확인해야 합니다.

A appears twice, B once and C not at all. One extra match offsets one lost record in the total. Inspect source-row multiplicities and unmatched keys alongside counts.

15. LEFT가 정확히 원행 수인 조건When does LEFT preserve exactly the left count?

가정 비결측 등호 LEFT에서 뒤 WHERE는 없습니다. 왼쪽에 등장하는 각 키의 오른쪽 일치 수가 0 또는 1이면 결과 행 수는 왼쪽 수와 같은가요? 일치하지 않는 오른쪽 중복은 어떤가요?

For nonmissing equality LEFT with no later WHERE, every key appearing on the left has zero or one right match. What is the result count? What about duplicate right keys absent on the left?

풀이와 확인할 이유Solution and explanation

같습니다. 각 왼쪽 행은 일치 1개 또는 NULL 확장 1개를 줍니다. 왼쪽에 없는 키의 오른쪽 중복은 이 LEFT 결과에 기여하지 않습니다. 따라서 오른쪽 전체 고유성은 충분한 계약이지만 이 특정 출력 개수의 필요조건까지는 아닙니다.

It equals the left count: each left row yields one match or one extension. Duplicates of right keys absent from the left contribute nothing. Global right uniqueness is sufficient but not necessary for this particular count equality.

16. 조건 없는 곱A Cartesian product

가정 표 L에 2행, R에 4행이 있고 모든 쌍을 만드는 CROSS JOIN을 합니다. 출력 단위와 개수는 무엇인가요?

Toy tables L and R have two and four rows. A CROSS JOIN takes every pair. What are its unit and count?

풀이와 확인할 이유Solution and explanation

출력은 L원행·R원행의 대응 쌍으로 2×4=8행입니다. 공통 개체를 식별한 조인이나 새로운 8관측이라고 자동으로 부르지 않습니다. 모든 조합을 만들겠다는 질문에 맞는지 확인합니다.

The unit is an L-record/R-record pair; there are eight. This does not automatically identify common entities or create eight new observations. It must fit the question of generating all combinations.

17. 조인 개수 공식을 증명하기Prove the cardinality formula

유한 표의 비결측 등호 키별 등장 수를 Lₖ,Rₖ라고 둡니다. INNER 결과가 ΣₖLₖRₖ인 이유와 LEFT에서 max(1,Rₖ)가 나오는 이유를 설명하세요.

For finite nonmissing equality keys with multiplicities Lₖ, Rₖ, justify the INNER sum ΣₖLₖRₖ and LEFT’s max(1, Rₖ).

풀이와 확인할 이유Solution and explanation

같은 키의 각 왼쪽 행과 각 오른쪽 행을 고르는 방법이 LₖRₖ개입니다. 다른 키의 쌍은 겹치지 않아 합합니다. LEFT는 Rₖ=0일 때도 왼쪽 각 행에 확장 1개를 주므로 Lₖmax(1,Rₖ)입니다. 후속 WHERE는 이 공식 이후에 따로 제외할 수 있습니다.

There are LₖRₖ ways to select the two source rows with key k. Distinct-key pair sets are disjoint. LEFT adds one extension for every left row when Rₖ=0, giving Lₖmax(1, Rₖ). A subsequent WHERE can further remove rows.

18. 암묵 가중 평균An implicitly weighted mean

가정 왼쪽 값 A=0,B=10이고 INNER의 오른쪽 대응 수가 A3개,B1개입니다. 원 평균과 조인 후 왼쪽 값 평균을 비교하세요.

Toy left values A=0, B=10 have three and one right INNER matches. Compare original and joined means.

풀이와 확인할 이유Solution and explanation

원 평균은 (0+10)/2=5이고 출력 평균은 (3×0+1×10)/4=2.5입니다. 원값은 같아도 A에 세 배의 가중치가 생겼습니다. 원행 균등 평균을 원한다면 조인의 대응 수를 따로 처리해야 합니다.

The original mean is five; the joined mean is 2.5. Match multiplicity weights A three times without changing its value. Preserve the original-row target rather than treating this as the same mean.

19. 평균 일치가 관계 일치는 아니다Mean agreement does not prove equal linkage weights

가정 왼쪽 두 값이 모두 10입니다. 조인 전에는 각각 1번, 조인 후에는 첫 행 3번·둘째 행 1번 나왔습니다. 두 평균이 같으니 가중치도 같다고 할 수 있나요?

Both toy left values are ten. Joining repeats the first three times and the second once. Does the unchanged mean establish unchanged weights?

풀이와 확인할 이유Solution and explanation

없습니다. 두 평균은 모두 10이지만 원행 비중은 1/2,1/2에서 3/4,1/4로 바뀌었습니다. 특정 값에 대한 같은 평균은 모든 값에서 같은 선형 요약을 한다는 증명이 아닙니다.

No. Both means are ten, but weights change from one-half each to three-quarters and one-quarter. Agreement on a particular value vector does not establish agreement for every possible vector.

20. 실제 국가 조합 수Actual country combination counts

실제 16국가 각각 45년인 두 표가 있습니다. 모든 ISO·연도 쌍은 각 표에서 고유합니다. ISO만 붙일 때와 ISO·연도를 붙일 때의 행 수 차이를 구하세요.

Each of two actual tables has sixteen countries over forty-five years, with unique ISO-year pairs. Compare ISO-only and ISO-year joins.

풀이와 확인할 이유Solution and explanation

ISO만이면 16×45×45=32,400조합, 같은 ISO·연도면 16×45=720행입니다. 차이는 31,680개의 교차연도 조합이며 추가 원관측이 아닙니다. 값이 미관측인 셀이 있어도 키 일치 개수와는 별도입니다.

ISO-only gives 32,400 combinations; ISO-year gives 720 rows. The additional 31,680 cross-year combinations are not new observations. Missing values remain separate from key-match cardinality.

21. 일치한 NULL과 없는 키Matched NULL and an absent key

가정 왼쪽 A,B,C와 오른쪽 (A,10),(B,NULL)을 키로 LEFT 조인합니다. B와 C의 value는 모두 NULL인데 어떤 열을 남겨 두 상태를 구별할 수 있나요?

Toy left keys A, B, C join right records (A,10),(B, NULL) using LEFT. Both B and C have NULL values. What should be retained to distinguish them?

풀이와 확인할 이유Solution and explanation

오른쪽의 원래 비결측 키 또는 별도로 선언한 존재 표지를 남깁니다. 키만으로 조인하면 B의 오른쪽 키는 B, C의 오른쪽 키는 NULL입니다. 원 오른쪽 키도 NULL일 수 있다면 이 진단의 전제가 사라지므로 별도 계약이 필요합니다.

Retain a right identifier declared nonmissing, or a separate presence marker. With key-only matching, B has right key B while C has NULL. Nullable original right keys require an additional contract.

22. = NULL의 성공한 오답An incorrect query that executes

값 열에 가정 값 10,NULL이 있습니다. WHERE value=NULL의 출력이 0행이면 원자료에 NULL이 없다는 뜻인가요?

A toy column contains 10 and NULL. WHERE value=NULL returns no rows. Does this establish no missing source values?

풀이와 확인할 이유Solution and explanation

아닙니다. 일반 등호에서 NULL 비교는 미지이므로 WHERE가 참으로 남기는 행이 없습니다. NULL을 찾는 조건은 IS NULL입니다. 질의 성공과 질문의 정확성은 다른 검토입니다.

No. Ordinary equality with NULL is unknown, and WHERE retains only true. Use IS NULL for missingness. Execution success does not establish that the intended question was expressed.

23. IS NULL의 두 행Two rows selected by IS NULL

가정 왼쪽 A,B,C, 오른쪽 (A,10),(B,NULL)을 키만으로 LEFT 조인한 뒤 WHERE r.value IS NULL을 적용합니다. 어떤 왼쪽 키가 남고, 모두 오른쪽 키가 원래 없었나요?

Toy left A, B, C joins right (A,10),(B, NULL) by key-only LEFT, then filters WHERE r.value IS NULL. Which remain, and are both originally absent keys?

풀이와 확인할 이유Solution and explanation

B와 C가 남습니다. B는 오른쪽 원키가 있고 값만 NULL이며 C만 원키가 없습니다. 따라서 value IS NULL을 원키 부재의 동의어로 쓰면 B까지 잘못 분류합니다.

B and C remain. B originally has a right key with a NULL value; only C lacks a key. A NULL value is not synonymous with original key absence.

24. ON과 WHERE의 개수Counts under ON and WHERE

가정 왼쪽 A,B,C, 오른쪽 (A,10),(B,NULL)에서 키 조건에 더해 value≥5를 씁니다. 조건을 ON에 둘 때와 LEFT 이후 WHERE에 둘 때 출력 수는?

Toy left A, B, C and right (A,10),(B, NULL) use a key condition plus value≥5. Compare placement in ON and after LEFT in WHERE.

풀이와 확인할 이유Solution and explanation

ON은 A의 일치와 B,C의 확장으로 3행입니다. WHERE는 키 조인 결과의 B,C를 미지 조건으로 제외하여 A의 1행입니다. 조건 위치가 결과를 바꿉니다. 설명의 논리 단계와 최적화기의 실제 물리 실행 순서는 구별합니다.

ON produces three rows: A matches, B and C are extended. WHERE retains only A, giving one row. Logical result semantics differ; this explanation does not prescribe physical optimizer order.

25. NULL 확장 2개와 원키 부재 1개Two extensions but one originally absent key

왼쪽 A,B,C·오른쪽 (A,10),(B,NULL)에 키 일치 AND value≥5인 LEFT를 적용합니다. 오른쪽 키NULL이 2개인데 원 오른쪽 키 부재도 2개인가요?

LEFT matches toy keys A, B, C to (A,10),(B, NULL) with key equality AND value≥5. Two output right keys are NULL. Were two original right keys absent?

풀이와 확인할 이유Solution and explanation

아닙니다. B는 원키가 있지만 값 조건에서 탈락하여 확장됐고 C는 원키 자체가 없습니다. 확장 2개와 원키 부재 1개를 별도로 셉니다. 출력 키만으로 원표 존재 상태를 역추론하지 않습니다.

No. B existed but failed the value predicate; only C was absent. Count two extensions separately from one original key absence. Output NULLs alone do not reconstruct original presence.

26. R의 NA 조건 벡터An R predicate containing NA

R 가정 값 x=c(10,NA_real_)에서 SQL WHERE x≥5와 같은 참 위치만 선택하려 합니다. 왜 !is.na(x) & x>=5를 명시하나요?

For R toy values x=c(10,NA_real_), why explicitly filter with !is.na(x) & x>=5 when emulating SQL WHERE x≥5?

풀이와 확인할 이유Solution and explanation

x≥5만 평가하면 TRUE,NA가 되고 자료틀의 직접 부분선택은 NA 행을 만들 수 있습니다. 가용성 조건을 더하면 TRUE,FALSE로 참 위치만 남깁니다. 이것은 명시한 대응 구현이지 모든 R 기본 동작이 SQL과 같다는 뜻은 아닙니다.

The comparison alone gives TRUE, NA, and direct data-frame subsetting can generate NA rows. The availability test makes TRUE, FALSE and retains only true positions. This is an explicit counterpart, not an assertion that all R defaults equal SQL.

27. 미지 논리의 간단한 경계Simple unknown-logic boundaries

이 장의 일반 SQL 논리에서 UNKNOWN AND FALSE와 UNKNOWN OR TRUE는 무엇인가요? WHERE는 UNKNOWN을 남기나요?

Under the ordinary SQL logic used here, evaluate UNKNOWN AND FALSE and UNKNOWN OR TRUE. Does WHERE retain UNKNOWN?

풀이와 확인할 이유Solution and explanation

각각 FALSE와 TRUE입니다. 첫 식은 다른 값이 무엇이든 거짓 항이 함께 필요하여 거짓이고, 둘째는 참 항 하나로 참입니다. WHERE는 TRUE만 남기므로 UNKNOWN은 남기지 않습니다. NULL을 항상 FALSE라고 치환해 모든 식에 적용하지 않습니다.

They are FALSE and TRUE respectively. WHERE retains only TRUE. Do not replace NULL or UNKNOWN by FALSE in every expression; that would change other logical results.

28. NULL이 포함된 NOT INNOT IN containing NULL

가정 SQL 표현 2 NOT IN (1,NULL)은 왜 단순히 TRUE라고 말할 수 없나요? 같은목적의 대안은 어떤 관계를 명시해야 하나요?

Why is toy SQL 2 NOT IN (1,NULL) not simply TRUE? What must an alternative state?

풀이와 확인할 이유Solution and explanation

2가 1과 다르다는 것은 참이지만 NULL과 다르다는 비교는 미지여서 전체 조건도 미지입니다. WHERE는 이를 남기지 않습니다. NOT EXISTS를 쓰는 경우에도 어느 키 조건의 일치가 존재하지 않는지를 명시하고 원키 NULL 계약을 확인해야 합니다.

Two differs from one, but comparison with NULL is unknown, leaving the condition unknown. WHERE discards it. A NOT EXISTS alternative must state the intended matching key condition and missing-key contract.

29. 행 5개와 가용값 3개Five rows and three available values

가정 그룹 A값(0,2),B값(NULL,4),C값(NULL)에서 전체 COUNT(*)와 COUNT(X)는 각각 얼마인가요? 관측 0의 역할도 쓰세요.

Toy groups are A:(0,2), B:(NULL,4), C:(NULL). Find overall COUNT(*) and COUNT(X), including the role of zero.

풀이와 확인할 이유Solution and explanation

전체 행은 5개, 가용값은 0,2,4의 3개입니다. 관측 0도 COUNT(X)에 들어갑니다. NULL을 세지 않는 것은 관측 0을 버리는 규칙이 아닙니다.

There are five rows and three non-NULL values:0,2,4. Observed zero contributes to COUNT(X). Excluding NULLs is not a rule to discard numerical zero.

30. 그룹별 SUM과 AVGGroup SUM and AVG

가정 A:(0,2),B:(NULL,4),C:(NULL)에서 수치형 입력 계약의 SQLite SUM(X),AVG(X),COUNT(X)를 그룹별로 구하세요.

For numerical SQLite input A:(0,2), B:(NULL,4), C:(NULL), calculate SUM(X), AVG(X), COUNT(X) per group.

풀이와 확인할 이유Solution and explanation

A는 합 2·평균 1·가용수 2, B는 합 4·평균 4·가용수 1, C는 합NULL·평균NULL·가용수 0입니다. C는 원행이 있으므로 그룹 자체는 나타납니다. SQL SUM의 빈 가용집합 계약을 수학의 빈합 0과 구별합니다.

A gives 2,1,2; B gives 4,4,1; C gives NULL, NULL,0. C still appears because it has a source row. SQL SUM’s empty-available-set contract differs from the mathematical empty-sum convention.

31. 0 대체 평균 비교A zero-replacement comparison

가정 A:(0,2),B:(NULL,4),C:(NULL)에서 AVG(COALESCE(X,0))를 구하고, 이 값이 원 결측을 복원한 평균인지 설명하세요.

For toy A:(0,2), B:(NULL,4), C:(NULL), find AVG(COALESCE(X,0)). Does it recover source truth?

풀이와 확인할 이유Solution and explanation

A1,B2,C0입니다. B와 C에서는 원래 미관측인 값을 0으로 가정한 비교입니다. 원 진실을 알아낸 것은 아니며 원 NULL 상태와 가정 대체를 따로 보존합니다.

The values are A1, B2, C0. B and C substitute assumed zeros for unavailable values. Preserve that assumption separately from original NULLs; it does not recover missing truth.

32. HAVING의 가용수 조건An available-count HAVING condition

가정 A:(0,2),B:(NULL,4),C:(NULL)를 GROUP BY한 뒤 HAVING COUNT(X)≥2를 적용합니다. 남는 그룹과 이 조건이 입력행 조건과 다른 이유를 쓰세요.

Group toy A:(0,2), B:(NULL,4), C:(NULL), then apply HAVING COUNT(X)≥2. Which group remains, and how does it differ from filtering input availability?

풀이와 확인할 이유Solution and explanation

가용수가 2인 A만 남습니다. HAVING은 그룹 집계 결과의 가용수를 비교합니다. WHERE X가용은 입력의 NULL 행을 먼저 없애는 별도 조건이고 그 자체로 그룹별 가용수 2이상을 검사한 것은 아닙니다.

Only A remains. HAVING tests an aggregate count per group. A WHERE availability filter removes input NULL rows but does not by itself require at least two available values per group.

33. 그룹 평균을 합칠 가중치Weights for pooling group means

가정 A의 가용평균 1·가용수 2, B의 가용평균 4·가용수 1입니다. 두 평균 균등 평균과 가용값 전체 평균을 구하세요.

Toy A has available mean 1/count 2 and B mean 4/count 1. Compare the equal-group and pooled available-value means.

풀이와 확인할 이유Solution and explanation

그룹 균등 평균은(1+4)/2=2.5이고 가용값 전체 평균은(2×1+1×4)/3=2입니다. 질문이 그룹 균등인지 원 가용값 균등인지에 따라 가중치가 달라집니다.

The equal-group mean is 2.5; the pooled available-value mean is 2. They use different targets. Pool the original available values with their corresponding valid counts.

34. 존재하지 않는 그룹An absent group

원표에는 가정 C행 한 개의 값NULL이 있고 D행은 없습니다. GROUP BY 결과에서 C와D는 어떻게 다르며 C평균을 0으로 써도 되나요?

A toy source contains one C row with NULL value and no D rows. Compare C and D under GROUP BY. Is C’s mean zero?

풀이와 확인할 이유Solution and explanation

C는 한 원행으로 존재하여 COUNT(*)1·COUNT(X)0·AVG(X)NULL이 나옵니다. D는 GROUP BY만으로 새로 만들어지지 않습니다. C평균NULL은 관측평균 0과 다르므로 0으로 바꾸지 않습니다.

C appears with COUNT(*)1, COUNT(X)0 and AVG(X) NULL. D is not generated merely by grouping. C’s undefined mean is not an observed zero mean.

35. LEFT 뒤 오른쪽을 세기Counting the right side after LEFT

가정 왼쪽 A,B,C, 오른쪽 (A,10),(B,NULL)을 키만으로 LEFT 조인합니다. COUNT(*),COUNT(r.key),COUNT(r.value)를 구하세요. 원 오른쪽 키는 비결측입니다.

Toy left A, B, C joins right (A,10),(B, NULL) by key-only LEFT. Original right keys are nonmissing. Find COUNT(*), COUNT(r.key), COUNT(r.value).

풀이와 확인할 이유Solution and explanation

각각 3,2,1입니다. C확장 행도 출력행이므로 COUNT(*)에 들어갑니다. 실제 대응 원키 A,B는 2개이고 가용 value는A10 하나입니다. 세 분모의 대상이 다릅니다.

They are 3,2,1. The C extension is an output row, A and B are two matched right keys, and only A has an available value. The three denominators concern different objects.

36. 실제 full과 available-only INNERActual full versus available-only INNER

실제 왼쪽 인원 키 3613개, full오른쪽 키 3613개(로그NULL603개), available-only오른쪽 키 3010개입니다. 각 INNER의 출력행과 가용로그 수는?

The actual left has 3613 person keys; full outcomes have 3613 keys with 603 NULL logs; available-only outcomes have 3010 keys. Count rows and available logs under each INNER.

풀이와 확인할 이유Solution and explanation

full INNER는 3613행·가용 3010개, available-only INNER는 3010행·가용 3010개입니다. full에서는 NULL값에도 키가 있고 available-only에서는 해당키가 없습니다. 값 가용수를 같게 보고 행관계도 같다고 바꾸지 않습니다.

Full INNER gives 3613 rows and 3010 logs; available-only INNER gives 3010 rows and 3010 logs. Equal available counts do not make the key relationships identical.

37. 실제 교육집단의 분모 합Actual schooling-group totals

실제 ≤12년 집단은 1806행·로그가용 1489개, >12년 집단은 1807행·가용 1521개입니다. 각 미관측 수와 전체 세 분모를 구하세요.

Actual ≤12-year and >12-year schooling groups have 1806/1807 rows and 1489/1521 available logs. Find missing counts and pooled totals.

풀이와 확인할 이유Solution and explanation

미관측은 317개와 286개입니다. 전체 원행 3613,가용 3010,미관측 603이며 3613=3010+603입니다. 같은 변수와 같은 제외 규칙의 가용수를 사용했는지도 확인합니다.

Missing counts are 317 and 286. Totals are 3613 source rows,3010 available logs and 603 unavailable logs. Use valid counts for the same variable and exclusion rule.

38. LEFT 후 WHERE의 대상 축소The target reduced by WHERE after LEFT

실제 인원 3613키에 available-only로그 3010키를 LEFT로 붙인 뒤 WHERE log_wage IS NOT NULL을 사용했습니다. 결과행 수와 원 질문의 변화를 설명하세요.

LEFT actual 3613 person keys to 3010 available-only outcome keys, then filter WHERE log_wage IS NOT NULL. Describe count and target.

풀이와 확인할 이유Solution and explanation

LEFT직후 3613행에서 가용로그 3010행만 남습니다. 원 인원 전부를 보존한 연결표에서 가용값 조건을 만족하는 대상표로 바뀌었습니다. LEFT라는 단어만 보고 최종출력도 전원을 보존한다고 쓰면 틀립니다.

The 3613-row joined table becomes 3010 available-log rows. The final target no longer preserves every original person. The word LEFT alone does not describe the final filtered result.

39. 407의 실제와 교차 조합Actual and crossed code 407 combinations

실제 원코드 407의 전후 원행 42·168을 코드로만 붙이면 4조합입니다. 같은 원행 변화 0,2.5 FTE와 교차변화 3.5,−1 FTE의 지위를 설명하세요.

Matching actual code 407 rows 42 and 168 by code creates four pairs. Classify same-row changes 0,2.5 FTE and crossed changes 3.5,−1 FTE.

풀이와 확인할 이유Solution and explanation

(42,42),(168,168)은 원행을 보존한 전후짝입니다. (42,168),(168,42)는 서로 다른 원행의 시점값을 교차시킨 고의 오류입니다. 네 수가 계산된다고 네 실제점포 변화를 관측한 것은 아닙니다.

Pairs(42,42),(168,168) preserve source-row wave links. Pairs(42,168),(168,42) deliberately cross different records. Four computable numbers are not four observed establishment changes.

40. 정상과 잘못된 점포 평균의 차이Difference between valid and invalid store means

실제 정상 완전 384짝의 평균은−541/7680 FTE이고, 고의 코드조인 완전 386조합의 평균은−491/7720 FTE입니다. 두 평균 차이(고의−정상)를 정확히 계산하고 해석하세요.

The actual 384 complete source-row pairs average−541/7680 FTE; deliberately invalid 386 code-only combinations average−491/7720. Calculate invalid minus valid exactly and interpret.

풀이와 확인할 이유Solution and explanation

차이는 10141/1482240 FTE입니다. 전체 합도 정상−541/20과 고의−491/20으로 다르고 분모도 384와 386입니다. 다른 원행을 연결해 만든 값이며 표본을 늘려 더 정밀한 같은대상 평균을 얻은 것이 아닙니다.

The difference is 10141/1482240 FTE. Sums also differ:−541/20 versus−491/20, over 384 versus 386 values. Invalid linkage changes both numerator and denominator rather than improving precision for an unchanged target.

41. 조인 평균과 공분산의 항등식A joined-mean covariance identity

n≥1개 원행의 가용값 yᵢ와 비음수 정수 반복수 mᵢ가 있고 Σmᵢ>0입니다. 원행 균등 공분산 Covₙ(m,y)=n⁻¹Σ(mᵢ−m̄)(yᵢ−ȳ)를 사용해 출력평균−원평균을 나타내세요.

For n≥1 available source values yᵢ and nonnegative integer multiplicities mᵢ with positive total, use the n-denominator source-uniform covariance Covₙ(m, y) to express joined minus source mean.

풀이와 확인할 이유Solution and explanation

반복수 평균 m̄>0입니다. 곱의 평균에서 평균의 곱을 빼는 항등식을 쓰면 됩니다.

yˉJ=my‾mˉyˉJ−yˉ=Cov⁡n(m,y)mˉ\begin{gathered}\bar y_J=\frac{\overline{my}}{\bar m}\\\bar y_J-\bar y=\frac{\operatorname{Cov}_n(m,y)}{\bar m}\end{gathered}

출력과 원값의 평균 차이는 반복수와 값의 관계에 달립니다. 공분산 0이면 같을 수 있지만 반복수가 모두 같다는 결론까지 나오지는 않습니다.

The mean multiplicity m̄ is positive. Apply mean product minus product of means:

yˉJ=my‾mˉyˉJ−yˉ=Cov⁡n(m,y)mˉ\begin{gathered}\bar y_J=\frac{\overline{my}}{\bar m}\\\bar y_J-\bar y=\frac{\operatorname{Cov}_n(m,y)}{\bar m}\end{gathered}

Zero covariance can preserve this mean without making all multiplicities equal.

42. 모든 값에서 평균을 보존할 조건Preserving the mean for every value vector

n≥1개 원행의 비음수 반복수 mᵢ와 Σmᵢ>0를 고정합니다. 모든 실수 값벡터 y에 대해 반복가중평균이 원 균등평균과 같으려면 어떤 조건이 필요한지 증명하세요.

Fix n≥1 nonnegative multiplicities with positive total. Prove the condition for preserving the source-uniform mean for every real vector y.

풀이와 확인할 이유Solution and explanation

j번째 값만 1이고 나머지는 0인 벡터를 넣으면 각 j에 대해 mⱼ/Σmᵢ=1/n이어야 합니다. 따라서 모든 반복수가 같은 양수여야 합니다. 반대로 그러면 공통수가 분자·분모에서 취소되어 모든 값에서 평균을 보존합니다.

mj∑imi=1n\frac{m_j}{\sum_i m_i}=\frac1n

특정 값 하나의 평균 일치보다 훨씬 강한 조건입니다.

Take y with value one at position j and zero elsewhere. Equality requires the normalized multiplicity at every j to be 1/n:

mj∑imi=1n\frac{m_j}{\sum_i m_i}=\frac1n

Thus all multiplicities must be equal and positive. Conversely, their common factor cancels. Agreement for one specific value vector is much weaker.

43. 원키 존재 표지의 전제A presence-marker prerequisite

LEFT 결과에서 오른쪽 id가NULL이면 원키가 없다고 판단하려 합니다. 원 오른쪽 id도NULL을 허용하고, 별도 비결측 조인열 k를 사용했다면 무엇이 문제인가요?

You infer no right record from a NULL right id after LEFT. But original right ids may be NULL and matching uses another nonmissing field k. What fails?

풀이와 확인할 이유Solution and explanation

일치한 오른쪽 원행의 id가 원래NULL일 수 있어 NULL확장과 구별되지 않습니다. 조인으로 만들어진 NULL인지 원래 값NULL인지 구분할 비결측 존재 표지나 별도 가용 키가 필요합니다. 값 상태만으로 원행 부재를 확정하지 않습니다.

A matched original record can itself have NULL id, making it indistinguishable from an extension on that field. Retain a declared nonmissing presence marker or another suitable identifier. A NULL value alone does not establish record absence.

44. DISTINCT가 잘못된 키를 고치는가Does DISTINCT repair an invalid key?

고의 다대다 조인 후 SELECT DISTINCT를 써서 행 수를 줄였습니다. 이것만으로 실제 관측 대응을 복구했다고 할 수 있나요?

A deliberately wrong many-to-many join is followed by SELECT DISTINCT. Does the smaller output establish repaired observational linkage?

풀이와 확인할 이유Solution and explanation

없습니다. DISTINCT는 선택한 출력 열의 같은 값을 축약합니다. 서로 다른 원행쌍이 같은 수치를 가지면 합쳐질 수 있고, 잘못된 쌍이 다른 값을 가지면 남을 수 있습니다. 원 단위·키·관계를 먼저 바로잡아야 합니다.

No. DISTINCT collapses equality on selected output fields. Different source pairs can collapse, while invalid pairs with different values remain. Repair the declared unit, keys and relationship rather than treating deduplication as linkage evidence.

45. 값NULL을 제외하지 않는 존재 질문An existence question that retains matched NULLs

가정 왼쪽 A,B,C와 오른쪽 (A,10),(B,NULL)에서 “같은 키의 오른쪽 기록이 없는 왼쪽”을 찾습니다. 답과 NOT EXISTS가 확인해야 할 조건은?

Toy left A, B, C and right(A,10),(B, NULL) have available keys. Find left records without any same-key right record. What should NOT EXISTS test?

풀이와 확인할 이유Solution and explanation

답은C입니다. NOT EXISTS는 오른쪽 값의 가용성이 아니라 오른쪽 키가 왼쪽 키와 일치하는 행의 존재를 검사해야 합니다. B는 값NULL이어도 대응 기록이 있습니다. 원키는 이 가정에서 모두 가용합니다.

Only C. Test existence of a matching right key, not availability of its value. B has a counterpart even with a NULL value.

46. 거래 집계 후 일대일 연결Aggregate transactions before a one-to-one linkage

가정 왼쪽 고객 A값 10,B값 30입니다. 오른쪽 거래는 A1,A2,B5입니다. 거래와 바로 붙인 왼쪽 값 평균, 오른쪽을 고객별로 먼저 집계해 한 행씩 붙인 왼쪽 값 평균은?

Toy customer values are A10, B30; transactions are A1, A2, B5. Compare the mean of left values after direct joining versus first making one right summary per customer.

풀이와 확인할 이유Solution and explanation

바로 붙이면 왼쪽 값 10,10,30의 평균 50/3입니다. 오른쪽을 고객별 한 행으로 만들고 A,B에 붙이면 원 왼쪽 평균 20입니다. 거래 합은A3,B5로 별도 유지할 수 있습니다. 두 평균의 차이는 고객과 거래의 가중 대상 차이입니다.

Direct joining averages 10,10,30 to 50/3. Joining one summary per customer retains the original customer mean 20. Transaction totals A3, B5 can be retained separately. The targets weight transactions versus customers differently.

47. 물음표는 테이블명이 아니다A placeholder is not a table name

Python sqlite3의 고정 SQL SELECT value FROM records WHERE id=?에 id값을 바인딩합니다. 같은 물음표로 테이블명 records도 바꿀 수 있다고 일반화해도 되나요?

Python sqlite3 binds an id value in SELECT value FROM records WHERE id=?. May the same placeholder mechanism be presumed to select table records?

풀이와 확인할 이유Solution and explanation

안 됩니다. 여기서 물음표는 데이터 값을 바인딩하는 위치입니다. 테이블·열 식별자 선택은 드라이버의 별도 규칙과 고정된 허용 목록 등을 사용해야 합니다. 값 바인딩을 임의 SQL구문 조립과 섞지 않습니다.

No. The placeholder binds a data value. Identifier selection needs a separate driver-aware design, such as fixed permitted identifiers. Do not confuse data binding with arbitrary SQL construction.

48. REAL과 정확 분수REAL and an exact fraction

실제 점포 원소수 평균을 Fraction으로−541/7680, SQLite AVG로 근사−0.0704427083이라고 얻었습니다. SQL이 틀렸거나 원소수가 무한정밀 측정이라는 결론인가요?

Actual retained source decimals give Fraction mean−541/7680 and approximate SQLite AVG−0.0704427083. Does this imply either a wrong query or infinitely precise measurement?

풀이와 확인할 이유Solution and explanation

둘 다 아닙니다. 정확 분수는 보존한 입력 소수에 대한 산술이고 REAL은 수치근사 연산입니다. 예상한 표시·반올림 차이와 계산오류를 구별해 대조합니다. 원측정의 오차·정밀도는 그 산술만으로 결정하지 않습니다.

Neither follows. The fraction is exact arithmetic on retained decimal inputs; REAL uses numerical approximation. Separate expected rounding from calculation errors. Measurement precision is not determined by this arithmetic.

49. 보관 조회와 임의 SQL 실행Archived retrieval versus arbitrary SQL execution

화면에 SQL 예상 메모를 쓴 뒤 “보관 결과 공개”를 눌렀습니다. 이것이 새 SQL을 실행했다거나 메모의 구문이 검증되었다는 뜻인가요?

A learner writes a SQL prediction note and clicks reveal archived result. Was that SQL executed or its syntax validated?

풀이와 확인할 이유Solution and explanation

아닙니다. 이 장의 브라우저는 고정된 실제 실행기록을 선택할 뿐입니다. 메모는 실행되지 않으며 구문검사 결과도 아닙니다. 새 코드의 의미와 실행을 확인하려면 내려받은 실제 환경의 새 프로세스를 사용합니다.

No. The browser selects a fixed actual record. Notes are not executed or syntax checked. A new program requires an actual fresh process and a review of its declared inputs and semantics.

50. 44개 실행과 실패 개수Forty-four runs and their failures

보관 프로그램은 키 8개·조인 12개·NULL8개·집계 6개·실제SQL10개입니다. 키의 반복·NULL 시나리오는 각 Python/R에서 실패하고 다른 프로그램은 성공했습니다. 총실행·실패·성공 수는?

Archived programs number 8 key checks,12 joins,8 NULL examples,6 aggregations and 10 actual-source queries. Duplicate/NULL keys fail in both Python and R; all others succeed. Count total, failures and successes.

풀이와 확인할 이유Solution and explanation

총 44개, 실패 4개, 성공 40개입니다. 실패를 실제 기록으로 남기는 것도 실행 증거입니다. 성공 40개가 모두 올바른 과학적 결론을 냈다는 뜻은 아니며 고의잘못된 조인도 종료는 성공합니다.

There are 44 actual runs,4 failures and 40 successes. Failures remain execution evidence. Successful exits include deliberately invalid joins and do not certify every substantive interpretation.

51. 원파일과 메모리 DB의 변경Source files and the memory database

실제 Python 프로그램이 새 메모리 DB에서 CREATE와 INSERT를 실행하고 SELECT했습니다. “데이터베이스를 전혀 변경하지 않았다”와 “원CSV·외부DB를 수정하지 않았다” 중 어느 표현이 맞나요?

An actual driver creates tables and inserts rows into a new memory database before SELECT. Did it change no database, or did it preserve original CSVs and external databases?

풀이와 확인할 이유Solution and explanation

후자입니다. 새 메모리 DB의 구조와 내용은 생성·적재했지만 원CSV와 외부DB를 수정하지 않았습니다. SELECT문 자체의 조회 성격과 전체 드라이버의 CREATE/INSERT까지 분리해 설명합니다.

It preserved original CSVs and external databases. The new memory database was created and populated. Distinguish SELECT’s query behavior from the driver’s CREATE/INSERT steps.

52. 같은 해시가 의미하는 것What an equal hash establishes

두 CSV의 SHA-256이 같고 보관한 바이트 비교도 같았습니다. 이것만으로 키가 현실 개체를 식별하고 원값이 참이라는 증명인가요?

Two CSVs have the same SHA-256 and their retained bytes are compared equal. Does that prove real-entity identifiers or true measurements?

풀이와 확인할 이유Solution and explanation

아닙니다. 이번 바이트 비교는 파일 동일성의 증거이지 관측의 의미·키 적합성·측정 진실성을 증명하지 않습니다. 해시·원행대응·수치검산·자료정의를 각 범위에 맞게 함께 사용합니다.

No. This is evidence of file-byte identity, not substantive key suitability or measurement truth. Combine hashes, source correspondence, arithmetic checks and definitions without conflating their scopes.

53. SELECT의 성공과 관측값의 증가A successful SELECT and more observations

고의 ISO-only SELECT가 32,400행을 내고 정상종료했습니다. 실제 관측 720행보다 많으니 정보가 45배가 되었다고 써도 되나요?

A deliberate ISO-only SELECT returns 32,400 rows successfully versus 720 actual country-years. Is there forty-five times as much observational information?

풀이와 확인할 이유Solution and explanation

안 됩니다. 원표를 재조합한 교차연도 짝 수가 늘었을 뿐 새관측을 수집하지 않았습니다. 정상종료는 SQL 실행상태이며 원단위의 정보나 독립 표본 수를 새로 인증하지 않습니다.

No. The query generated cross-year combinations without collecting new observations. Successful execution does not establish a larger source sample or independent information count.

54. 동률을 남긴 ORDER BYORDER BY with unresolved ties

가정 결과 두 행은 같은 key=A이고 서로 다른 원행쌍(1,2),(1,3)입니다. ORDER BY key만으로 두 행의 표시 순서가 결정되나요?

Toy output rows share key A but have source pairs(1,2),(1,3). Does ORDER BY key alone determine their order?

풀이와 확인할 이유Solution and explanation

결정되지 않습니다. key가 동률이므로 두 순서를 모두 허용할 수 있습니다. 재현에 그 순서가 필요하면 양쪽 원행 등 구별되는 추가정렬키를 명시합니다. source번호의 의미도 이번 보관 범위로 제한합니다.

No. The ordering field ties. If tie order matters, add distinguishing source positions or another declared tie-breaker. A source-position key still refers to its archive scope.

55. LIMIT이 분모를 바꾼다LIMIT changes the selected denominator

가정 고객 100명 표에서 ORDER BY 없이 LIMIT10으로 출력한 평균을 전체 100명 평균 또는 무작위 10명 표본평균이라고 부를 수 있나요?

A toy 100-customer table is queried with LIMIT 10 and no ORDER BY. May its mean be called the full mean or a random ten-customer sample mean?

풀이와 확인할 이유Solution and explanation

없습니다. 어떤 10행인지의 순서·선택 규칙이 명시되지 않았고 무작위 추출도 수행하지 않았습니다. 제한된 출력의 요약을 전체표적이나 확률표집 결과로 바꾸어 해석하지 않습니다.

No. The selected ordering is not declared and random sampling was not performed. A limited output is not automatically the full target or a probability sample.

56. 비고유 코드와 서로 다른 원행A nonunique code with distinct source records

실제 코드 407의 원행 42와 168이 서로 다른 주·체인·FTE를 담습니다. 한 코드를 PRIMARY KEY로 만들려고 한 행을 먼저 지워도 될까요?

Actual code 407 rows 42 and 168 differ in state, chain and FTE. May one be deleted merely to make the code a primary key?

풀이와 확인할 이유Solution and explanation

그 근거만으로는 안 됩니다. 이번 코드의 비고유성과 원행추적을 보존하고 관계에 맞는 키를 설계해야 합니다. 두 행이 같은 측정 개체의 오입력 복사라는 증거가 없으므로 임의삭제를 검증된 정정이라고 부르지 않습니다.

Not on that evidence. Preserve the nonunique code and source traces, and choose keys suited to the relationship. Without evidence of accidental duplicate entry, deletion is not a verified correction.

57. 집계 항등식의 정확 분모Exact denominators in pooling

가용값을 겹침없는 유한 집단으로 나눴고 각 가용수 n_g≥1,합도 양수입니다. 집단평균의 n_g가중평균이 전체가용평균임을 증명하세요.

Finite disjoint groups partition available values. Every included valid count n_g≥1 and total count is positive. Prove that weighting their means by n_g gives the pooled available mean.

풀이와 확인할 이유Solution and explanation

각 n_g x̄_g는 해당집단의 가용값 합입니다. 겹침없는 전체분할이므로 합을 더하면 전체가용값 합이 됩니다.

∑gngxˉg=∑ixixˉ=∑gngxˉg∑gng\begin{gathered}\sum_g n_g\bar x_g=\sum_i x_i\\\bar x=\frac{\sum_g n_g\bar x_g}{\sum_g n_g}\end{gathered}

분모는 원명부 크기가 아니라 같은 변수의 가용수입니다. 가용 0집단은 평균을 만들어 곱하지 않고 따로 처리합니다.

Each n_g x̄_g is that group’s available-value sum. The partition therefore gives

∑gngxˉg=∑ixixˉ=∑gngxˉg∑gng\begin{gathered}\sum_g n_g\bar x_g=\sum_i x_i\\\bar x=\frac{\sum_g n_g\bar x_g}{\sum_g n_g}\end{gathered}

Use valid counts for the same variable rather than roster sizes. Zero-available groups require separate handling.

58. 세 표의 다중 대응Multiplicity across three tables

세 유한표의 비결측 키 등호 INNER에서 키A 등장 수가 각각 2,3,4이고 다른키는 없습니다. 최종조합 수와 이것이 독립관측 수가 아닌 이유를 설명하세요.

Three finite tables use nonmissing equality INNER joins on their only key A, with multiplicities 2,3,4. Count final combinations and explain their observational status.

풀이와 확인할 이유Solution and explanation

최종조합은 2×3×4=24개입니다. 각 행은 세 원행을 고르는 조합입니다. 같은 원행들이 여러 조합에 반복되므로 24개의 새로운 독립개체를 관측했다는 뜻은 아닙니다. 실제 3표가 어떤 관계인지 먼저 선언해야 합니다.

There are 24 combinations, each selecting one source row from each table. Reused source records do not become 24 new independent entities. The substantive three-table relationship must be declared first.

59. LEFT도 평균을 보존하지 않을 수 있다LEFT need not preserve a mean

가정 왼쪽 A=0,B=10,C=20이고 오른쪽 키는 A,A,B이며 C는 없습니다. LEFT 이후 왼쪽 값 평균을 원평균과 비교하세요.

Toy left values are A0, B10, C20; right keys are A, A, B with C absent. Compare the mean of left values after LEFT with the source mean.

풀이와 확인할 이유Solution and explanation

원평균은 10입니다. LEFT출력은 0,0,10,20으로 평균 30/4=7.5입니다. C를 NULL확장으로 남겼어도 A의 증폭 때문에 원행 균등가중치가 바뀝니다. 왼쪽원행 보존과 왼쪽값 평균보존은 다른 성질입니다.

The original mean is 10; LEFT gives 0,0,10,20 and mean 7.5. Preserving C by extension does not prevent A’s amplification. Left-row preservation differs from equal-source-weight mean preservation.

60. 연구 주장 전체를 바로잡기Repair the full research claim

“SQL이 성공했고 LEFT를 썼으니 전원이 한 번씩 남았고,NULL은 모두 0이므로 평균은 전체모집단 값이며 전후차이는 정책효과다”를 고치세요.

Repair: “Successful SQL plus LEFT preserves everyone once; all NULLs are zeros, so the mean equals the population value and before/after change is a policy effect.”

풀이와 확인할 이유Solution and explanation

“고정 SQL의 실행은 성공했다. 원행별 다중·미일치 대응과 후속 WHERE를 확인해 최종출력의 단위·개수를 보고한다. NULL값과 없는키·관측 0을 구별하고 가용평균 또는 명시한 대체가정 평균을 쓴다. 대표성·독립성·정책 인과효과에는 별도 설계와 가정이 필요하다”라고 범위를 맞춥니다.

State that the fixed query executed successfully. Audit multiplicity, unmatched rows and later WHERE filters before reporting final units and counts. Distinguish NULL values, absent keys and observed zero; label available means or explicit replacement assumptions. Population representativeness, independence and causal policy effects need separate evidence.

자료와 출처Data and sources

실습에 추가한 실제 입력과 출처Additional observed lab inputs and provenance

실제 자료 사례Actual-data cases · 원자료·단위·결측·변환·출처Inputs, units, missingness, transformations and sources

자료별 확보일·원행 식별·단위·이용 조건은 출처 기록을 확인하세요. 학습 사본은 제공처의 현재 최신 자료와 다를 수 있습니다.Consult each source record for retrieval dates, row identifiers, units and terms. Teaching copies can differ from current provider releases.

자료사전·출처·이용 조건Data dictionary, sources and terms