참고 자료 · 68
데이터 조인 무결성
조인은 행을 늘려 합계를 왜곡할 수 있습니다.
업데이트됨 · 13 min
이 가이드가 달성하는 목표
- 행의 단위 정의
- 결합 전에 집계
- 누락된 대응 확인
빠른 확인
- 행의 의미를 정의하고 조인 전후 키, 개수, 합계를 비교하세요.
- 중복 제거가 잘못된 관계를 가릴 수 있습니다.
단계별 방법
- 1
행의 단위 정의
주문 테이블의 한 행은 주문을, 항목 테이블의 한 행은 주문 내 상품을 나타냅니다. 결합 전에 반복 키와 NULL 키를 확인합니다.
각 테이블의 행 단위와 키를 기록합니다.
- 2
결합 전에 집계
주문 키별로 항목을 집계합니다. 그 결과를 주문과 결합하면 상품마다 주문 금액이 반복되지 않습니다. 원래 주문 테이블의 합계와 비교합니다.
두 쿼리와 합계를 보관합니다.
- 3
누락된 대응 확인
LEFT JOIN은 항목이 없는 주문도 남기지만, 오른쪽 테이블에 적용한 WHERE 조건이 이를 제거할 수 있습니다. 대응 없음과 금액 0은 다릅니다.
제외된 주문과 필터 규칙을 기록합니다.
재현 가능한 수락 사례
가상 예시입니다. 고객이나 실제 관측 결과를 나타내지 않습니다.
사례 입력 보기
{
"orders": [
{
"id": 1,
"total": 100
},
{
"id": 2,
"total": 200
}
],
"line_order_ids": [
1,
1,
2
],
"sum_before": 300,
"sum_after_raw_join": 400
}예상 판단
400은 주문 하나를 중복 계산합니다. 주문별로 항목을 집계하여 300을 복원합니다. 각각 100인 가상 주문 두 건도 시험합니다. 합계는 200입니다. SUM(DISTINCT total)은 100을 반환하여 유효한 값을 제거합니다. 금액 중복 제거 대신 식별자와 조인 관계의 수를 확인합니다.
재현 가능한 SQL 쿼리
가상 예: 주문 금액 100과 200, 주문 1, 1, 2에 연결된 항목 세 개입니다. 쿼리는 VALUES만 사용하며 테스트 환경에서 실행하세요.
WITH orders(id, total) AS (VALUES (1, 100), (2, 200)),
lines(order_id) AS (VALUES (1), (1), (2))
SELECT COUNT(*) AS rows, SUM(o.total) AS total
FROM orders o JOIN lines l ON l.order_id = o.id;WITH orders(id, total) AS (VALUES (1, 100), (2, 200)),
lines(order_id) AS (VALUES (1), (1), (2)),
per_order AS (
SELECT order_id, COUNT(*) AS line_count
FROM lines GROUP BY order_id
)
SELECT COUNT(*) AS orders, SUM(o.total) AS total
FROM orders o LEFT JOIN per_order l ON l.order_id = o.id;직접 결합하면 세 행과 합계 400이 나옵니다. 먼저 집계하면 주문 두 건과 합계 300을 얻습니다.
WITH orders(id, total) AS (VALUES (1, 100), (2, 100))
SELECT SUM(total) AS correct_total,
SUM(DISTINCT total) AS distinct_total
FROM orders;금액이 100과 100이면 올바른 합계는 200이지만 SUM(DISTINCT total)은 100입니다.
검증 절차
- 주문과 항목의 세분성을 정의합니다.
- 두 항목을 가진 주문을 결합합니다.
- 키, 행 수 및 대조한 합계를 보존합니다.
메커니즘 구분
| 메커니즘 | 목적 | 검증 또는 제한 |
|---|---|---|
| INNER JOIN | 일치하는 행 유지 | 항목 없는 주문은 제외 |
| LEFT JOIN | 왼쪽 주문 모두 유지 | 후속 필터가 제거할 수 있음 |
| SUM(DISTINCT total) | 동일한 금액 제거 | 서로 다른 주문도 금액이 같을 수 있음 |
관리 지표
| 지표 | 측정 대상 | 첫 번째 조치 |
|---|---|---|
| COUNT(*) | 주문 테이블의 한 행은 주문을, 항목 테이블의 한 행은 주문 내 상품을 나타냅니다. 결합 전에 반복 키와 NULL 키를 확인합니다. | 각 테이블의 행 단위와 키를 기록합니다. |
| SUM(total) | 주문 키별로 항목을 집계합니다. 그 결과를 주문과 결합하면 상품마다 주문 금액이 반복되지 않습니다. 원래 주문 테이블의 합계와 비교합니다. | 두 쿼리와 합계를 보관합니다. |
일반적인 실수
- 항목 없는 주문은 제외
- 후속 필터가 제거할 수 있음
- 서로 다른 주문도 금액이 같을 수 있음
자주 묻는 질문
SUM(DISTINCT total)이면 충분한가요?
아닙니다. 금액 100인 주문 두 건의 합계는 200이지만 SUM(DISTINCT total)은 100을 반환합니다. 금액 중복 제거 대신 키 관계를 수정하세요.
조인 카디널리티, NULL 및 집계
이 언어판의 상세 참고 설명은 영어로 제공됩니다.
A join transforms a set of rows before metrics are computed. To investigate a difference, inspect the resulting pairs and removed records: comparing two sums is insufficient. This workshop follows two fictional sources through to six aggregates without connecting to a database.
Documentary reference: PostgreSQL 18, chapters 7.2, 9.2 and 9.21, reviewed on 23 October 2026. Data, scenarios and acceptance suggestions are original CIE examples. They describe no real company, person or observed performance.
PostgreSQL 18 · Table expressions · PostgreSQL 18 · documentation reviewed 2026-10-23
Four reference points for reading a join
| Reference point | Documented SQL effect | Acceptance question |
|---|---|---|
| Pairs and cardinality | Each true match produces a pair; LEFT null-extends left rows with no match. | How many right rows match each left identifier? |
| ON and WHERE | ON decides matches before LEFT extension; WHERE then retains only rows with a true predicate. | Does the filter define the relationship or final population? |
| NULL keys | Ordinary equality with NULL yields unknown. IS NOT DISTINCT FROM treats two nulls as not distinct. | Does matching two missing values make business sense? |
| Aggregates | COUNT(*) counts rows; COUNT(expression) counts non-null values; SUM ignores null values. | What is the contribution grain and what does a missing value mean? |
PostgreSQL 18 · Comparison functions · PostgreSQL 18 · documentation reviewed 2026-10-23
Two fictional six-row sources
Each left row is an independent technical record identified by l.id; metric is an integer quantity with no business unit. A right row is a state associated with a key. Key A repeats on both sides; row identifiers are unique and non-null. NULL denotes a missing value, never the text “NULL”. L4’s zero is a present measurement. Left baseline: 6 rows, 5 non-null measurements and SUM(metric) = 430; one measurement is unknown, so this is not a complete total of every quantity.
| l.id | l.key | l.metric |
|---|---|---|
| L1 | A | 100 |
| L2 | A | 200 |
| L3 | B | 50 |
| L4 | C | 0 |
| L5 | NULL | 80 |
| L6 | D | NULL |
| r.id | r.key | r.state |
|---|---|---|
| R1 | A | active |
| R2 | A | inactive |
| R3 | B | active |
| R4 | NULL | active |
| R5 | E | active |
| R6 | D | NULL |
행 대조 워크숍
Choose INNER or LEFT, the position of r.state = 'active', key comparison and a full or empty right source. The 24 configurations are bounded to these data. The result table shows each pair and null-extended rows. Six aggregates apply to the result after any WHERE filter.
This local reader executes no SQL, collects no data and offers no import or export. It covers no collations, type conversion, composite keys, temporal joins, permissions, performance or other SQL dialects. Identifier ordering is added for readability; a join alone does not guarantee this order.
Keep the left reference of 430 over five known measurements for comparison. An unchanged sum after joining does not establish matching quality: duplication and exclusion may offset each other.
최종 행 결과
| l.id | l.key | l.metric | r.id | r.key | r.state | Pair status |
|---|
Row query corresponding to the choices
lab_left, lab_right and lab_right_empty are illustrative names; lab_right_empty has the lab_right schema with zero rows. Displayed code explains the choices and is not executed. Aggregates below are computed over these rows without GROUP BY.
What the six results actually count
| Expression | Reading in this exercise |
|---|---|
| COUNT(*) | All final rows, including null-extended LEFT rows. |
| COUNT(DISTINCT l.id) | Distinct retained left identifiers. This count does not repair a repeated sum. |
| COUNT(r.id) | Rows with an actual right record: source r.id is always non-null. |
| COUNT(r.key) | Non-null right keys. May be below COUNT(r.id) when a null-key record matched. |
| COUNT(l.metric) | Occurrences of non-null left measurements, including repetitions; zero counts as present. |
| SUM(l.metric) | Sum of non-null values after joining. NULL when no non-null value contributes, including an empty result. |
PostgreSQL 18 · Aggregate functions · PostgreSQL 18 · documentation reviewed 2026-10-23
Nine explained scenarios, available without JavaScript
J01 · LEFT with repeated key A
| Join / filter / keys / right source | Expected reading |
|---|---|
| LEFT / none / equal / full | 8 rows, 6 left identifiers, 6 present r.id, 6 present r.key, 7 present measurements; sum 730. A produces four pairs. |
J02 · INNER and removed records
| Join / filter / keys / right source | Expected reading |
|---|---|
| INNER / none / equal / full | 6 rows, 4 left identifiers, 5 measurements; sum 650. L4 and L5 disappear; A duplication remains. |
J03 · Active filter in ON
| Join / filter / keys / right source | Expected reading |
|---|---|
| LEFT / on / equal / full | 6 rows and 6 left identifiers; 3 present r.id, 5 measurements; sum 430. L4, L5 and L6 retain null-extended right values. |
J04 · Same filter in WHERE
| Join / filter / keys / right source | Expected reading |
|---|---|
| LEFT / where / equal / full | 3 rows and 3 left identifiers; sum 350. The filter removes rows without active state, including null-extended rows. |
J05 · Two null keys matched
| Join / filter / keys / right source | Expected reading |
|---|---|
| LEFT / none / safe / full | 8 rows, 7 present r.id but 6 present r.key; sum 730. L5 actually matches R4; null r.key therefore does not establish an unmatched row. |
J06 · Misleading equal sum
| Join / filter / keys / right source | Expected reading |
|---|---|
| INNER / where / safe / full | 4 rows, 4 left identifiers and sum 430: same sum as the baseline, although L4 and L6 are absent. Equal totals do not mean equal populations. |
J07 · Empty result and null sum
| Join / filter / keys / right source | Expected reading |
|---|---|
| INNER / none / equal / empty | No rows. All five COUNT values are 0; SUM(l.metric) is NULL. The reader does not replace this absence with zero. |
J08 · Empty right, preserved left
| Join / filter / keys / right source | Expected reading |
|---|---|
| LEFT / none / equal / empty | 6 rows, 6 left identifiers, no present r.id or r.key; 5 measurements and sum 430. Left values remain present. |
J09 · WHERE removes every extended row
| Join / filter / keys / right source | Expected reading |
|---|---|
| LEFT / where / equal / empty | LEFT first produces six extended rows; the active WHERE predicate removes all of them. Five COUNT values 0, sum NULL. |
Prepare evidence for a reliable reconciliation
| Suggested check | Useful record |
|---|---|
| Grain and keys | Describe one row in each source, its identifiers and expected business cardinality. Repeated keys may be legitimate. |
| Scope and state | Fix period, time zone, source versions and relevant state date before joining. |
| Matches | List records with zero, one or several matches; retain identifiers from both sides. |
| Missing values | Separate null key, null measurement, null state and absent right record. Do not replace all four with zero. |
| Aggregation | Compare at the business grain before and after joining. Document any allocation rule and reconcile its result. |
| Regression | Keep repeated keys, null keys, zero, unknown measurement and empty-source cases; check rows as well as totals. |
In this exercise two left A rows and two right A rows produce four pairs without a filter. Removing a right row or applying DISTINCT without understanding its role can lose valid information. Choose prior aggregation, a more precise key or an allocation rule only after defining the business need.
Sources, edition and credits
Official PostgreSQL Global Development Group documentation, edition 18. Original CIE summary, fictional data and educational reader; no PostgreSQL engine or code is embedded. References describe the selected semantics and do not certify this reader.
PostgreSQL 18 · Table expressions · PostgreSQL 18 · documentation reviewed 2026-10-23
SHA-256 : 252f02babbaec8ac702ff2966db75d0b38886cb576a90bbfc458bc4abd0dc688
PostgreSQL 18 · Aggregate functions · PostgreSQL 18 · documentation reviewed 2026-10-23
SHA-256 : c466d05fe796e77f1362dae39c8b212c7bf381065904eb555fa91537e363e5d0
PostgreSQL 18 · Comparison functions · PostgreSQL 18 · documentation reviewed 2026-10-23
SHA-256 : f08404f5624f8b87a91f117be7d59feca075508b124552b66b61940b5b6ef28c
공식 참조
참조는 방법을 뒷받침합니다. 상황에 맞게 검사를 조정하십시오. 이는 인증이 아닙니다. 원본 참조 제목 및 소스 문서는 다른 언어로 작성되었을 수 있습니다.
참고 자료 확인일 .
