100 Exercises / SQL / 100 Exercises to SQL for Data Analysis
Analyze factories, parts, and inspections with SQL JOINs
Join factory, part, and inspection tables in SQL. Check unmatched records, duplicate keys, defect costs, and changes in row counts after joins.
SQL 100 Exercises Chapter 5 (No.041–No.050): Table Join with JOIN
This article is Chapter 5 in the “100 Exercises for SQL Basics for Data Analysis” series. In Chapter 4 (No.031–040), we learned about dates, strings, and calculations. In this chapter, we use JOIN(Table binding) to analyze factory masters, production lines, component masters, and inspection records. We aggregate and analyze data cross-sectionally. We will also practice automatic detection methods for data inconsistencies.
Note
This material is a notebook previously used by Surikobo (or personally by the representative, Hiroshi Wayama), and has been reconstructed, edited, and published with the company’s permission. All data listed is fictional and has no relation whatsoever to real companies, factories, or figures.
Introduction: Practical Challenges in Manufacturing Covered in This Article
This is a challenge Mr. Watanabe from the IT and Data Management Department at an automotive parts manufacturer.
Consistency verification and cross-sectional analysis of manufacturing performance database data (monthly regular work)
1. Check whether the inspection record database factory_id/part_code exists in each master table.
2. Combine factory master × inspection records to aggregate production KPIs by line and factory
3. Combine parts master × inspection records to calculate defect loss amounts for each part.
4. Identify parts and factories without inspection records and set master maintenance priorities
Currently, I am comparing master Excel files with performance CSVs using VLOOKUP, As data increases, processing becomes heavier, leading to missed responses.
By using JOIN in SQL, the matching of multiple tables can be completed in 1query, Automatic detection of inconsistent data is also possible.
Common workplace tasks
| Scene | Current Challenges | What SQL JOIN can solve |
|---|---|---|
| Summary of Results by Factory | Factory code → Factory name conversion manually done with VLOOKUP | Automatically assign factory names to INNER JOIN factories |
| Calculation of Loss Amount for Parts | Manage unit price tables and performance tables separately | JOIN parts Combine unit prices to calculate the loss amount |
| Identification of Uninspected Parts | Manually check by comparing the master and achievements | Automatic extraction with LEFT JOIN ... WHERE IS NULL |
| Detecting Malicious Code | Visually check whether the code for the achievement data exists in the master | Automatic detection by LEFT JOIN ... WHERE IS NULL |
| Joining three or more tables | Combining multiple VLOOKUPs to complicate | Chain multiple JOIN and solve it in a single query |
JOIN is a core skill for Data Quality Management and KPI cross-sectional analysis in manufacturing.
Common pitfalls
Here are four points that JOIN beginners often stumble over.
1. Distinguishing Between INNER JOIN and LEFT JOIN
-- INNER JOIN: Only data matching both tables is retrieved (mismatches excluded)
SELECT * FROM inspections INNER JOIN parts ON inspections.part_code = parts.part_code;
-- LEFT JOIN: Hold all rows in the left table (if there is no match in the right table, NULL)
SELECT * FROM parts LEFT JOIN inspections ON parts.part_code = inspections.part_code;
INNER JOIN is used when you want to aggregate only data that exists reliably. LEFT JOIN is used when you want to detect data that doesn’t exist (master maintenance or quality control).
2. Increase in line count due to duplicate combination keys
If a join key matches multiple rows, the join can multiply the input rows. Compare COUNT(*) before and after the join to detect unintended duplication.
3. Use IS NULL to determine NULL
The joined sequence of rows that did not match in LEFT JOIN becomes NULL.
WHERE joined_col = NULL evaluates to UNKNOWN and selects no rows.
Always use WHERE joined_col IS NULL.
4. Verification of Number of Cases Before and After Joining
If the number of cases differs from expectations, it may be due to duplicate merging keys, NULL, or master inconsistency.
Check step by step in SELECT COUNT(*) FROM ....
Exercises in this chapter
| No. | Titles | Applications in manufacturing |
|---|---|---|
| 041 | Join tables with INNER JOIN | Inspection Records × Basic Integration of Factory Masters |
| 042 | Join one table based on LEFT JOIN | Identifying factories with zero inspection records based on all factories |
| 043 | Understanding the RIGHT JOIN Concept | Understanding the equivalence relationship with LEFT JOIN |
| 044 | Integrating factory master and inspection records | Aggregation of Results with Factory Name and Regional Information |
| 045 | Combining the part master with inspection records | Calculation of loss amount with unit price information attached |
| 046 | Join multiple tables | Four-table cross-table analysis: factory + line + parts + inspection records |
| 047 | Pay attention to duplicate binding keys | Tracking Increase in Number of Rows Due to Duplicate Quality Standards Tables |
| 048 | Confirm the increase in the number of cases after merging | Ensuring data quality through verification of number of transactions before and after JOIN |
| 049 | Extracting parts without inspection records | Identifying uninspected parts and prioritizing master maintenance |
| 050 | Detecting inspection records that do not exist in the component master | Detection of Malicious Codes and Data Quality Management |
Preparing the Python environment
Run each article in a fresh Jupyter Notebook kernel, from top to bottom, including the folded setup cells. [IN: n] and [OUT: n] identify matching input and output. The outputs were checked by rerunning the examples; version information and query plans may differ by environment. The font setting targets macOS; choose an installed Japanese font on other systems. Existing shared charts retain their original Japanese labels.
import platform
print(f"OS: {platform.system()} {platform.release()}")
print(f"Python: {platform.python_version()}")
OS: Darwin 25.5.0
Python: 3.14.4
import sqlite3
import numpy as np
import polars as pl
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.patches import Patch
matplotlib.rcParams['font.family'] = 'Hiragino Maru Gothic Pro'
%config InlineBackend.figure_format = 'svg'
np.random.seed(42)
print(f"sqlite3 : {sqlite3.sqlite_version}")
print(f"polars : {pl.__version__}")
print(f"numpy : {np.__version__}")
print(f"matplotlib: {matplotlib.__version__}")
print()
print("Library loading complete")
sqlite3 : 3.50.4
polars : 1.42.1
numpy : 2.5.1
matplotlib: 3.11.0
Library loading complete
Creating sample data
Scenario: Automotive parts manufacturer manufacturing record database / Data Management Department Table Structure: 5 tables
| Table Name | number of cases | Description |
|---|---|---|
factories | 5 items | Factory master (F05: Sendai Factory has no inspection record) |
lines | 8 items | Line master (factory code held as FK) |
parts | 8 items | Parts master (BRK-002 / ELC-002 / SUS-002 have no inspection record) |
quality_specs | 11 items | Quality standards table (some parts hold multiple standards = duplicate key) |
inspections | 73 items | Inspection records (no F05 record + part_code fraud cases included) |
JOIN Design Points for Demos:
factoriesNo inspection record at F05 (Sendai Factory) Emerges from → No.042 LEFT JOIN- Extracted with → No.049 for three parts of
parts(BRK-002 / ELC-002 / SUS-002) without inspection record inspectionsDetected in 3 cases withpart_code = 'UNKNOWN-999'(invalid part code) → No.050quality_specspart_codepartially overlapped (before and after the revision of the standard) → No.047 confirmed
Show setup code and output (input 3)
# ─────────────────────────────────────────────────────────────────────────
# SQL Helper Function
# ─────────────────────────────────────────────────────────────────────────
def q(conn, sql):
'''SQL Run Polars DataFrame Display results'''
print('── SQL ─────────────────────────────────────────')
for line in sql.strip().split('\n'):
print(f' {line}')
print('───────────────────────────────────────────────')
cur = conn.execute(sql.strip())
rows = cur.fetchall()
cols = [d[0] for d in cur.description]
data = {col: [row[i] for row in rows] for i, col in enumerate(cols)}
df = pl.DataFrame(data)
print(df)
print(f'↳ {len(rows)} rows retrieved')
return df
# ─────────────────────────────────────────────────────────────────────────
# Creating an in-memory database
# ─────────────────────────────────────────────────────────────────────────
conn = sqlite3.connect(':memory:')
conn.execute('''
CREATE TABLE factories (
factory_id TEXT PRIMARY KEY,
factory_name TEXT NOT NULL,
city TEXT NOT NULL,
region TEXT NOT NULL,
capacity INTEGER NOT NULL
)''')
conn.execute('''
CREATE TABLE lines (
line_code TEXT PRIMARY KEY,
factory_id TEXT NOT NULL,
line_name TEXT NOT NULL,
capacity_per_shift INTEGER NOT NULL
)''')
conn.execute('''
CREATE TABLE parts (
part_code TEXT PRIMARY KEY,
part_name TEXT NOT NULL,
category TEXT NOT NULL,
unit_price INTEGER NOT NULL,
supplier_code TEXT NOT NULL
)''')
conn.execute('''
CREATE TABLE quality_specs (
spec_id INTEGER PRIMARY KEY,
part_code TEXT NOT NULL,
spec_type TEXT NOT NULL,
max_dr_pct REAL NOT NULL,
effective_from TEXT NOT NULL
)''')
conn.execute('''
CREATE TABLE inspections (
id INTEGER PRIMARY KEY,
inspection_date TEXT NOT NULL,
factory_id TEXT NOT NULL,
line_code TEXT NOT NULL,
part_code TEXT NOT NULL,
shift TEXT NOT NULL,
production_qty INTEGER NOT NULL,
defect_qty INTEGER NOT NULL,
inspector_code TEXT NOT NULL
)''')
# ── Master Data ───────────────────────────────────────────────────────────
conn.executemany('INSERT INTO factories VALUES (?,?,?,?,?)', [
('F01', 'Tokyo Factory', 'Tokyo', 'Kanto', 2000),
('F02', 'Osaka Factory', 'Osaka Prefecture', 'Kansai', 1800),
('F03', 'Nagoya Factory', 'Aichi Prefecture', 'Central region', 1600),
('F04', 'Fukuoka Factory', 'Fukuoka Prefecture', 'Kyushu', 1200),
('F05', 'Sendai Factory', 'Miyagi Prefecture', 'Northeast', 1000), # No inspection record (JOIN demo)
])
conn.executemany('INSERT INTO lines VALUES (?,?,?,?)', [
('LINE-A1', 'F01', 'Engine parts line', 400),
('LINE-A2', 'F01', 'Brake Parts Line', 300),
('LINE-B1', 'F02', 'Engine parts line', 380),
('LINE-B2', 'F02', 'Electrical Components Line', 200),
('LINE-C1', 'F03', 'Suspension line', 150),
('LINE-C2', 'F03', 'Brake Parts Line', 280),
('LINE-D1', 'F04', 'Engine parts line', 350),
('LINE-E1', 'F05', 'Electrical Components Line', 180), # F05 Line (No track record)
])
conn.executemany('INSERT INTO parts VALUES (?,?,?,?,?)', [
('ENG-001', 'piston ring', 'Engine parts', 1200, 'SUP-01'),
('ENG-002', 'Crankshaft', 'Engine parts', 8500, 'SUP-01'),
('BRK-001', 'brake pad', 'brake parts', 950, 'SUP-02'),
('BRK-002', 'brake caliper', 'brake parts', 4200, 'SUP-02'), # No achievements
('ELC-001', 'Alternator', 'electrical components', 6800, 'SUP-03'),
('ELC-002', 'Starter motor', 'electrical components', 3500, 'SUP-03'), # No achievements
('SUS-001', 'shock absorber', 'suspension', 2800, 'SUP-04'),
('SUS-002', 'coil spring', 'suspension', 1800, 'SUP-04'), # No achievements
])
conn.executemany('INSERT INTO quality_specs VALUES (?,?,?,?,?)', [
(1, 'ENG-001', 'standard standard', 2.00, '2024-01-01'),
(2, 'ENG-001', 'Strict standards', 1.50, '2024-03-01'), # duplicate key
(3, 'ENG-002', 'standard standard', 1.80, '2024-01-01'),
(4, 'ENG-002', 'Strict standards', 1.20, '2024-03-01'), # duplicate key
(5, 'BRK-001', 'standard standard', 2.50, '2024-01-01'),
(6, 'BRK-001', 'Strict standards', 2.00, '2024-03-01'), # duplicate key
(7, 'BRK-002', 'standard standard', 3.00, '2024-01-01'),
(8, 'ELC-001', 'standard standard', 3.50, '2024-01-01'),
(9, 'ELC-001', 'Strict standards', 3.00, '2024-03-01'), # duplicate key
(10, 'ELC-002', 'standard standard', 3.00, '2024-01-01'),
(11, 'SUS-001', 'standard standard', 2.80, '2024-01-01'),
# SUS-002 has no standards
])
# ── Generation of inspection record data (7 lines, × 5 days× 2 shifts = 70 cases + 3 cases of fraud = 73 cases)──
np.random.seed(42)
LINE_CONFIG = {
'LINE-A1': ('F01', 'ENG-001', 'INS-001', 460, 0.018),
'LINE-A2': ('F01', 'BRK-001', 'INS-002', 300, 0.020),
'LINE-B1': ('F02', 'ENG-001', 'INS-003', 380, 0.019),
'LINE-B2': ('F02', 'ELC-001', 'INS-004', 200, 0.030),
'LINE-C1': ('F03', 'SUS-001', 'INS-005', 150, 0.025),
'LINE-C2': ('F03', 'BRK-001', 'INS-006', 280, 0.021),
'LINE-D1': ('F04', 'ENG-002', 'INS-007', 350, 0.022),
# LINE-E1 (F05) does not generate
}
DATES = ['2024-01-10', '2024-01-17', '2024-01-24', '2024-02-07', '2024-02-14']
SHIFTS = ['early shift', 'late shift']
records = []
rid = 1
for date in DATES:
for line_code, (factory_id, part_code, inspector, base_prod, base_dr) in LINE_CONFIG.items():
for shift in SHIFTS:
prod = int(np.clip(
np.random.normal(base_prod, base_prod * 0.05),
base_prod * 0.85, base_prod * 1.15
))
dr = base_dr + np.random.normal(0, base_dr * 0.15)
dr = max(dr, 0.005)
defect = max(1, round(prod * dr))
records.append((rid, date, factory_id, line_code, part_code, shift,
prod, defect, inspector))
rid += 1
# Fraud part_code 3 cases (No.050 for demo)
for extra in [
(rid, '2024-01-15', 'F01', 'LINE-A1', 'UNKNOWN-999', 'early shift', 450, 8, 'INS-001'),
(rid+1, '2024-01-22', 'F02', 'LINE-B1', 'UNKNOWN-999', 'late shift', 375, 12, 'INS-003'),
(rid+2, '2024-02-10', 'F03', 'LINE-C1', 'UNKNOWN-999', 'early shift', 148, 9, 'INS-005'),
]:
records.append(extra)
conn.executemany('INSERT INTO inspections VALUES (?,?,?,?,?,?,?,?,?)', records)
conn.commit()
print('Database creation completed')
for tbl in ['factories', 'lines', 'parts', 'quality_specs', 'inspections']:
n = conn.execute(f'SELECT COUNT(*) FROM {tbl}').fetchone()[0]
print(f' {tbl:<16}: {n} records')
print()
note = conn.execute(
"SELECT COUNT(*) FROM inspections WHERE part_code='UNKNOWN-999'"
).fetchone()[0]
print(f' ※ inspections Fraud among them part_code number of cases: {note}')
Database creation completed
factories : 5 records
lines : 8 records
parts : 8 records
quality_specs : 11 records
inspections : 73 records
※ inspections Fraud among them part_code number of cases: 3
Show setup code and output (input 4)
# ── Data summary graph (by factory: number of inspections / weighted average defect rate)─────────────────────
rows = conn.execute('''
SELECT f.factory_id, f.factory_name,
COUNT(i.id) AS n_insp,
COALESCE(SUM(i.production_qty), 0) AS total_prod,
COALESCE(SUM(i.defect_qty), 0) AS total_defect
FROM factories f
LEFT JOIN inspections i
ON f.factory_id = i.factory_id
AND i.part_code != 'UNKNOWN-999'
GROUP BY f.factory_id, f.factory_name
ORDER BY f.factory_id
''').fetchall()
fac_ids = [r[0] for r in rows]
fac_names = [r[1] for r in rows]
n_insps = [r[2] for r in rows]
t_prod = [r[3] for r in rows]
t_def = [r[4] for r in rows]
dr_vals = [d / p * 100 if p > 0 else 0.0 for d, p in zip(t_def, t_prod)]
# F05 (Sendai) is gray
COLORS = ['#4878CF', '#6ACC65', '#D65F5F', '#B47CC7', '#AAAAAA']
fig, axes = plt.subplots(1, 2, figsize=(13, 5))
for ax, vals, ylabel, title, fmt in [
(axes[0], n_insps, 'Number of Tests', 'By Factory Number of Tests (2024year1〜2month)', '{:.0f}'),
(axes[1], dr_vals, 'Weighted average defect rate (%)', 'By Factory Weighted average defect rate (2024year1〜2month)', '{:.2f}%'),
]:
bars = ax.bar(range(len(fac_ids)), vals, color=COLORS, alpha=0.85,
edgecolor='black', linewidth=0.4)
for bar, v in zip(bars, vals):
label = fmt.format(v)
ax.text(bar.get_x() + bar.get_width() / 2, bar.get_height() + 0.02,
label, ha='center', va='bottom', fontsize=9)
ax.set_title(title, fontsize=12, pad=10)
ax.set_xlabel('Factory', fontsize=10)
ax.set_ylabel(ylabel, fontsize=10)
ax.set_xticks(range(len(fac_ids)))
ax.set_xticklabels(
[f'{fid}\n{fn}' for fid, fn in zip(fac_ids, fac_names)], fontsize=8
)
ax.grid(axis='y', alpha=0.3)
legend_h = [Patch(color='#AAAAAA', alpha=0.85, label='F05: Sendai Factory (No inspection record)')]
axes[0].legend(handles=legend_h, fontsize=8, loc='upper right')
plt.tight_layout()
plt.show()
print('Data overview graph display completed (SVG 1/2)')
Data overview graph display completed (SVG 1/2)
No.041: Join Tables with INNER JOIN
Practical use
INNER JOIN retrieves 2Common parts of the tables (data matching both).
Main use cases in manufacturing:
- Creating highly readable reports by attaching factory names and regions to inspection records
- Combine parts master and performance to calculate loss amounts
- Only achievement records with valid master codes are counted
How the SQL works
The binding key will be Rows that do not exist on one table are automatically excluded..
This differs from the traditional comma conjunction using WHERE clauses; the intent is clear.
-- Modern Writing Style (Recommended)
SELECT * FROM A INNER JOIN B ON A.key = B.key;
-- Traditional Writing Style (Not Recommended)
SELECT * FROM A, B WHERE A.key = B.key;
Run in Python
# No.041: INNER JOIN — Inspection Records × Factory Master
print('=== INNER JOIN: Factory information is attached to inspection records (first10Item)===')
q(conn, '''
SELECT i.id,
i.inspection_date,
i.factory_id,
f.factory_name,
f.region,
i.line_code,
i.production_qty,
i.defect_qty
FROM inspections i
INNER JOIN factories f ON i.factory_id = f.factory_id
ORDER BY i.id
LIMIT 10
''')
print()
print('=== INNER JOIN Subsequent full confirmation of the number of cases ===')
q(conn, '''
SELECT COUNT(*) AS inner_join_count
FROM inspections i
INNER JOIN factories f ON i.factory_id = f.factory_id
''')
=== INNER JOIN: Factory information is attached to inspection records (first10Item)===
── SQL ─────────────────────────────────────────
SELECT i.id,
i.inspection_date,
i.factory_id,
f.factory_name,
f.region,
i.line_code,
i.production_qty,
i.defect_qty
FROM inspections i
INNER JOIN factories f ON i.factory_id = f.factory_id
ORDER BY i.id
LIMIT 10
───────────────────────────────────────────────
shape: (10, 8)
┌─────┬──────────────┬────────────┬──────────────┬─────────┬───────────┬──────────────┬────────────┐
│ id ┆ inspection_d ┆ factory_id ┆ factory_name ┆ region ┆ line_code ┆ production_q ┆ defect_qty │
│ --- ┆ ate ┆ --- ┆ --- ┆ --- ┆ --- ┆ ty ┆ --- │
│ i64 ┆ --- ┆ str ┆ str ┆ str ┆ str ┆ --- ┆ i64 │
│ ┆ str ┆ ┆ ┆ ┆ ┆ i64 ┆ │
╞═════╪══════════════╪════════════╪══════════════╪═════════╪═══════════╪══════════════╪════════════╡
│ 1 ┆ 2024-01-10 ┆ F01 ┆ Tokyo ┆ Kanto ┆ LINE-A1 ┆ 471 ┆ 8 │
│ ┆ ┆ ┆ Factory ┆ ┆ ┆ ┆ │
│ 2 ┆ 2024-01-10 ┆ F01 ┆ Tokyo ┆ Kanto ┆ LINE-A1 ┆ 474 ┆ 10 │
│ ┆ ┆ ┆ Factory ┆ ┆ ┆ ┆ │
│ 3 ┆ 2024-01-10 ┆ F01 ┆ Tokyo ┆ Kanto ┆ LINE-A2 ┆ 296 ┆ 6 │
│ ┆ ┆ ┆ Factory ┆ ┆ ┆ ┆ │
│ 4 ┆ 2024-01-10 ┆ F01 ┆ Tokyo ┆ Kanto ┆ LINE-A2 ┆ 323 ┆ 7 │
│ ┆ ┆ ┆ Factory ┆ ┆ ┆ ┆ │
│ 5 ┆ 2024-01-10 ┆ F02 ┆ Osaka ┆ Kansai ┆ LINE-B1 ┆ 371 ┆ 8 │
│ ┆ ┆ ┆ Factory ┆ ┆ ┆ ┆ │
│ 6 ┆ 2024-01-10 ┆ F02 ┆ Osaka ┆ Kansai ┆ LINE-B1 ┆ 371 ┆ 7 │
│ ┆ ┆ ┆ Factory ┆ ┆ ┆ ┆ │
│ 7 ┆ 2024-01-10 ┆ F02 ┆ Osaka ┆ Kansai ┆ LINE-B2 ┆ 202 ┆ 4 │
│ ┆ ┆ ┆ Factory ┆ ┆ ┆ ┆ │
│ 8 ┆ 2024-01-10 ┆ F02 ┆ Osaka ┆ Kansai ┆ LINE-B2 ┆ 182 ┆ 5 │
│ ┆ ┆ ┆ Factory ┆ ┆ ┆ ┆ │
│ 9 ┆ 2024-01-10 ┆ F03 ┆ Nagoya ┆ Central ┆ LINE-C1 ┆ 142 ┆ 4 │
│ ┆ ┆ ┆ Factory ┆ region ┆ ┆ ┆ │
│ 10 ┆ 2024-01-10 ┆ F03 ┆ Nagoya ┆ Central ┆ LINE-C1 ┆ 143 ┆ 3 │
│ ┆ ┆ ┆ Factory ┆ region ┆ ┆ ┆ │
└─────┴──────────────┴────────────┴──────────────┴─────────┴───────────┴──────────────┴────────────┘
↳ 10 rows retrieved
=== INNER JOIN Subsequent full confirmation of the number of cases ===
── SQL ─────────────────────────────────────────
SELECT COUNT(*) AS inner_join_count
FROM inspections i
INNER JOIN factories f ON i.factory_id = f.factory_id
───────────────────────────────────────────────
shape: (1, 1)
┌──────────────────┐
│ inner_join_count │
│ --- │
│ i64 │
╞══════════════════╡
│ 73 │
└──────────────────┘
↳ 1 rows retrieved
| inner_join_count |
|---|
| i64 |
| 73 |
Interpreting the results
factory_nameandregionhave been added to inspection records, greatly improving readability- The total number of
INNER JOINis 73records (equal to the total number of inspections). You can verify that validfactory_idexist in all test records - Three cases of fraud
part_code = 'UNKNOWN-999'were not ruled out becausefactory_idwere normal. Detect mismatches when coupling with the component master (No.045, No.050)
No.042: Join One Table Based on a LEFT JOIN
Practical use
LEFT JOIN Hold the entire row of the left table and complements NULL if there is no match in the right table.
Main use cases in manufacturing:
- View a list of all factories and visualize Factories without inspection records with NULL
- View a list of all items and identify Uninspected Parts
- “All-Checking Completeness” to comprehensively check all items present in the master
How the SQL works
With the same join condition and selected columns, a LEFT JOIN includes all INNER JOIN matches and also keeps unmatched left rows. SQL results may contain duplicates; the formula is a schematic inclusion relationship.
| Situation | INNER JOIN | LEFT JOIN |
|---|---|---|
| Lines matching A and B | ✅ exert effort | ✅ exert effort |
| A line that exists only in A | ❌ except | ✅ Output (NULL on side B) |
| A line that exists only in B | ❌ except | ❌ except |
Run in Python
# No.042: LEFT JOIN — Aggregates inspection performance based on all factories (F05 is displayed as 0 items)
print('=== LEFT JOIN: Number of inspections completed at all factories (F05 is NULL / 0 (It will be)===')
q(conn, '''
SELECT f.factory_id,
f.factory_name,
f.region,
f.capacity,
COUNT(i.id) AS inspection_count,
COALESCE(SUM(i.production_qty), 0) AS total_prod,
COALESCE(SUM(i.defect_qty), 0) AS total_defect
FROM factories f
LEFT JOIN inspections i ON f.factory_id = i.factory_id
GROUP BY f.factory_id, f.factory_name, f.region, f.capacity
ORDER BY inspection_count DESC
''')
=== LEFT JOIN: Number of inspections completed at all factories (F05 is NULL / 0 (It will be)===
── SQL ─────────────────────────────────────────
SELECT f.factory_id,
f.factory_name,
f.region,
f.capacity,
COUNT(i.id) AS inspection_count,
COALESCE(SUM(i.production_qty), 0) AS total_prod,
COALESCE(SUM(i.defect_qty), 0) AS total_defect
FROM factories f
LEFT JOIN inspections i ON f.factory_id = i.factory_id
GROUP BY f.factory_id, f.factory_name, f.region, f.capacity
ORDER BY inspection_count DESC
───────────────────────────────────────────────
shape: (5, 7)
┌────────────┬─────────────────┬───────────┬──────────┬────────────────┬────────────┬──────────────┐
│ factory_id ┆ factory_name ┆ region ┆ capacity ┆ inspection_cou ┆ total_prod ┆ total_defect │
│ --- ┆ --- ┆ --- ┆ --- ┆ nt ┆ --- ┆ --- │
│ str ┆ str ┆ str ┆ i64 ┆ --- ┆ i64 ┆ i64 │
│ ┆ ┆ ┆ ┆ i64 ┆ ┆ │
╞════════════╪═════════════════╪═══════════╪══════════╪════════════════╪════════════╪══════════════╡
│ F01 ┆ Tokyo Factory ┆ Kanto ┆ 2000 ┆ 21 ┆ 8046 ┆ 157 │
│ F02 ┆ Osaka Factory ┆ Kansai ┆ 1800 ┆ 21 ┆ 6158 ┆ 140 │
│ F03 ┆ Nagoya Factory ┆ Central ┆ 1600 ┆ 21 ┆ 4395 ┆ 101 │
│ ┆ ┆ region ┆ ┆ ┆ ┆ │
│ F04 ┆ Fukuoka Factory ┆ Kyushu ┆ 1200 ┆ 10 ┆ 3466 ┆ 78 │
│ F05 ┆ Sendai Factory ┆ Northeast ┆ 1000 ┆ 0 ┆ 0 ┆ 0 │
└────────────┴─────────────────┴───────────┴──────────┴────────────────┴────────────┴──────────────┘
↳ 5 rows retrieved
| factory_id | factory_name | region | capacity | inspection_count | total_prod | total_defect |
|---|---|---|---|---|---|---|
| str | str | str | i64 | i64 | i64 | i64 |
| "F01" | "Tokyo Factory" | "Kanto" | 2000 | 21 | 8046 | 157 |
| "F02" | "Osaka Factory" | "Kansai" | 1800 | 21 | 6158 | 140 |
| "F03" | "Nagoya Factory" | "Central region" | 1600 | 21 | 4395 | 101 |
| "F04" | "Fukuoka Factory" | "Kyushu" | 1200 | 10 | 3466 | 78 |
| "F05" | "Sendai Factory" | "Northeast" | 1000 | 0 | 0 | 0 |
Interpreting the results
- F05(Sendai Factory) is displayed as
inspection_count = 0andtotal_prod = 0. In INNER JOIN, the F05 line itself disappeared, but in LEFT JOIN, it resurfaces - By using
COALESCE(SUM(...), 0), NULL is converted to 0. If the total value of F05 remains NULL, errors may occur in subsequent calculations - With the discovery of factories with no inspection records, we are now discussing whether it was before operations started or if there was a data linkage gap. It can be an opportunity to conduct research. This is a crucial confirmation that serves as the starting point for data quality management
No.043: Understanding the Concept of RIGHT JOIN
Practical use
RIGHT JOIN is the reverse version of LEFT JOIN, and it Hold the entire row of the right table.
A RIGHT JOIN B is equivalent to B LEFT JOIN A.
In practice, LEFT JOIN (rearranging table order) is preferred over RIGHT JOIN.
Reason: LEFT JOIN makes it intuitive and easy to understand what to use as a standard.
How the SQL works
With the same join condition and selected columns, the matched rows are equivalent. Column order under SELECT * and row order without ORDER BY need not be identical.
| How to write | Holding side | excluded side |
|---|---|---|
A LEFT JOIN B | All lines of A | B-only row |
A RIGHT JOIN B | All lines of B | A line only |
A FULL OUTER JOIN B | All rows from both sides | None (supported since SQLite 3.39.0) |
Run in Python
# No.043: RIGHT JOIN — Confirm the result is the same as the LEFT JOIN in No.042
print('=== RIGHT JOIN(inspections Left,factories (right)===')
df_right = q(conn, '''
SELECT f.factory_id,
f.factory_name,
COUNT(i.id) AS inspection_count
FROM inspections i
RIGHT JOIN factories f ON i.factory_id = f.factory_id
GROUP BY f.factory_id, f.factory_name
ORDER BY f.factory_id
''')
print()
print('=== equivalent LEFT JOIN(Swapping table order)===')
df_left = q(conn, '''
SELECT f.factory_id,
f.factory_name,
COUNT(i.id) AS inspection_count
FROM factories f
LEFT JOIN inspections i ON f.factory_id = i.factory_id
GROUP BY f.factory_id, f.factory_name
ORDER BY f.factory_id
''')
right_vals = sorted(df_right['inspection_count'].to_list())
left_vals = sorted(df_left['inspection_count'].to_list())
print()
print(f'RIGHT JOIN Number of Results: {len(df_right)}')
print(f'LEFT JOIN Number of Results: {len(df_left)}')
print(f'The two are equivalent.: {right_vals == left_vals}')
=== RIGHT JOIN(inspections Left,factories (right)===
── SQL ─────────────────────────────────────────
SELECT f.factory_id,
f.factory_name,
COUNT(i.id) AS inspection_count
FROM inspections i
RIGHT JOIN factories f ON i.factory_id = f.factory_id
GROUP BY f.factory_id, f.factory_name
ORDER BY f.factory_id
───────────────────────────────────────────────
shape: (5, 3)
┌────────────┬─────────────────┬──────────────────┐
│ factory_id ┆ factory_name ┆ inspection_count │
│ --- ┆ --- ┆ --- │
│ str ┆ str ┆ i64 │
╞════════════╪═════════════════╪══════════════════╡
│ F01 ┆ Tokyo Factory ┆ 21 │
│ F02 ┆ Osaka Factory ┆ 21 │
│ F03 ┆ Nagoya Factory ┆ 21 │
│ F04 ┆ Fukuoka Factory ┆ 10 │
│ F05 ┆ Sendai Factory ┆ 0 │
└────────────┴─────────────────┴──────────────────┘
↳ 5 rows retrieved
=== equivalent LEFT JOIN(Swapping table order)===
── SQL ─────────────────────────────────────────
SELECT f.factory_id,
f.factory_name,
COUNT(i.id) AS inspection_count
FROM factories f
LEFT JOIN inspections i ON f.factory_id = i.factory_id
GROUP BY f.factory_id, f.factory_name
ORDER BY f.factory_id
───────────────────────────────────────────────
shape: (5, 3)
┌────────────┬─────────────────┬──────────────────┐
│ factory_id ┆ factory_name ┆ inspection_count │
│ --- ┆ --- ┆ --- │
│ str ┆ str ┆ i64 │
╞════════════╪═════════════════╪══════════════════╡
│ F01 ┆ Tokyo Factory ┆ 21 │
│ F02 ┆ Osaka Factory ┆ 21 │
│ F03 ┆ Nagoya Factory ┆ 21 │
│ F04 ┆ Fukuoka Factory ┆ 10 │
│ F05 ┆ Sendai Factory ┆ 0 │
└────────────┴─────────────────┴──────────────────┘
↳ 5 rows retrieved
RIGHT JOIN Number of Results: 5
LEFT JOIN Number of Results: 5
The two are equivalent.: True
Interpreting the results
- You can confirm that the results of RIGHT JOIN and LEFT JOIN (rearranging the table order) are exactly the same
- SQLite 3.39.0 and later support both
RIGHT JOINandFULL OUTER JOIN. - When emulating a full join on older SQLite versions, add only the unmatched rows from the other side with
UNION ALLto avoid double-counting matches.
No.044: Combining Factory Master and Inspection Records
Practical use
Factory Master (factory name, region, capacity) and Test Record (number of productions and defects) By JOINing, you can automatically generate KPI summaries for regions and factories.
Examples of use in manufacturing:
- Automation of Factory-Specific Monthly Production Reports for Management Meetings
- Comparison of defect rates by region (Kanto / Kansai / Chubu / Kyushu)
- Utilization rate analysis comparing capacity (
capacity) and actual production numbers
How the SQL works
When calculating the amount of defect loss, the cost gap (labor and equipment costs) by factory is
factories You can handle this by extending the table.
Run in Python
# No.044: Factory Master × Inspection Records — Factory-Specific KPI Aggregation (Exclusion of Invalid Part Codes)
print('=== By Factory KPI Summary (INNER JOIN + Except for invalid part codes)===')
q(conn, '''
SELECT f.factory_id,
f.factory_name,
f.region,
f.capacity,
COUNT(i.id) AS n_records,
SUM(i.production_qty) AS total_prod,
SUM(i.defect_qty) AS total_defect,
ROUND(SUM(i.defect_qty) * 100.0 / SUM(i.production_qty), 2) AS dr_pct,
ROUND(SUM(i.production_qty) * 1.0 / f.capacity, 1) AS prod_per_capacity
FROM factories f
INNER JOIN inspections i ON f.factory_id = i.factory_id
WHERE i.part_code != 'UNKNOWN-999'
GROUP BY f.factory_id, f.factory_name, f.region, f.capacity
ORDER BY dr_pct DESC
''')
=== By Factory KPI Summary (INNER JOIN + Except for invalid part codes)===
── SQL ─────────────────────────────────────────
SELECT f.factory_id,
f.factory_name,
f.region,
f.capacity,
COUNT(i.id) AS n_records,
SUM(i.production_qty) AS total_prod,
SUM(i.defect_qty) AS total_defect,
ROUND(SUM(i.defect_qty) * 100.0 / SUM(i.production_qty), 2) AS dr_pct,
ROUND(SUM(i.production_qty) * 1.0 / f.capacity, 1) AS prod_per_capacity
FROM factories f
INNER JOIN inspections i ON f.factory_id = i.factory_id
WHERE i.part_code != 'UNKNOWN-999'
GROUP BY f.factory_id, f.factory_name, f.region, f.capacity
ORDER BY dr_pct DESC
───────────────────────────────────────────────
shape: (4, 9)
┌────────────┬────────────┬────────────┬──────────┬───┬───────────┬───────────┬────────┬───────────┐
│ factory_id ┆ factory_na ┆ region ┆ capacity ┆ … ┆ total_pro ┆ total_def ┆ dr_pct ┆ prod_per_ │
│ --- ┆ me ┆ --- ┆ --- ┆ ┆ d ┆ ect ┆ --- ┆ capacity │
│ str ┆ --- ┆ str ┆ i64 ┆ ┆ --- ┆ --- ┆ f64 ┆ --- │
│ ┆ str ┆ ┆ ┆ ┆ i64 ┆ i64 ┆ ┆ f64 │
╞════════════╪════════════╪════════════╪══════════╪═══╪═══════════╪═══════════╪════════╪═══════════╡
│ F04 ┆ Fukuoka ┆ Kyushu ┆ 1200 ┆ … ┆ 3466 ┆ 78 ┆ 2.25 ┆ 2.9 │
│ ┆ Factory ┆ ┆ ┆ ┆ ┆ ┆ ┆ │
│ F02 ┆ Osaka ┆ Kansai ┆ 1800 ┆ … ┆ 5783 ┆ 128 ┆ 2.21 ┆ 3.2 │
│ ┆ Factory ┆ ┆ ┆ ┆ ┆ ┆ ┆ │
│ F03 ┆ Nagoya ┆ Central ┆ 1600 ┆ … ┆ 4247 ┆ 92 ┆ 2.17 ┆ 2.7 │
│ ┆ Factory ┆ region ┆ ┆ ┆ ┆ ┆ ┆ │
│ F01 ┆ Tokyo ┆ Kanto ┆ 2000 ┆ … ┆ 7596 ┆ 149 ┆ 1.96 ┆ 3.8 │
│ ┆ Factory ┆ ┆ ┆ ┆ ┆ ┆ ┆ │
└────────────┴────────────┴────────────┴──────────┴───┴───────────┴───────────┴────────┴───────────┘
↳ 4 rows retrieved
| factory_id | factory_name | region | capacity | n_records | total_prod | total_defect | dr_pct | prod_per_capacity |
|---|---|---|---|---|---|---|---|---|
| str | str | str | i64 | i64 | i64 | i64 | f64 | f64 |
| "F04" | "Fukuoka Factory" | "Kyushu" | 1200 | 10 | 3466 | 78 | 2.25 | 2.9 |
| "F02" | "Osaka Factory" | "Kansai" | 1800 | 20 | 5783 | 128 | 2.21 | 3.2 |
| "F03" | "Nagoya Factory" | "Central region" | 1600 | 20 | 4247 | 92 | 2.17 | 2.7 |
| "F01" | "Tokyo Factory" | "Kanto" | 2000 | 20 | 7596 | 149 | 1.96 | 3.8 |
Interpreting the results
- With
regionassigned, it becomes possible to compare Kanto vs Kansai vs Chubu vs Kyushu prod_per_capacitydivides period production by daily factory capacity. It does not account for operating days and is not the utilization rate in the formula above; it cannot by itself establish spare capacity.- F05 (Sendai) will not appear in the results due to INNER JOIN. If you want to display all factories, use LEFT JOIN from No.042
No.045: Combining Part Master and Inspection Records
Practical use
By JOINING the Parts Master (part name, category, unit price) and Test Record, You can calculate the “defect loss amount” or “production value” for each part in a single query.
Examples of use in manufacturing:
- Prioritizing improvement investments (starting with parts with large losses)
- Comparison of KPIs by Category (Engine / Brakes / Electrical / Suspension)
- ROI estimation based on unit price × number of defects
How the SQL works
Since the unit price of the component master is applied to each row after JOIN,
SUM(i.defect_qty * p.unit_price) can be calculated correctly.
Run in Python
# No.045: Parts Master × Inspection Records — Loss Ranking by Part
print('=== By Component Production Value and Defect Loss (INNER JOIN)===')
q(conn, '''
SELECT p.part_code,
p.part_name,
p.category,
p.unit_price,
COUNT(i.id) AS n_records,
SUM(i.production_qty) AS total_prod,
SUM(i.defect_qty) AS total_defect,
ROUND(SUM(i.defect_qty) * 100.0 / SUM(i.production_qty), 2) AS dr_pct,
SUM(i.production_qty * p.unit_price) AS production_value,
SUM(i.defect_qty * p.unit_price) AS defect_loss
FROM parts p
INNER JOIN inspections i ON p.part_code = i.part_code
GROUP BY p.part_code, p.part_name, p.category, p.unit_price
ORDER BY defect_loss DESC
''')
=== By Component Production Value and Defect Loss (INNER JOIN)===
── SQL ─────────────────────────────────────────
SELECT p.part_code,
p.part_name,
p.category,
p.unit_price,
COUNT(i.id) AS n_records,
SUM(i.production_qty) AS total_prod,
SUM(i.defect_qty) AS total_defect,
ROUND(SUM(i.defect_qty) * 100.0 / SUM(i.production_qty), 2) AS dr_pct,
SUM(i.production_qty * p.unit_price) AS production_value,
SUM(i.defect_qty * p.unit_price) AS defect_loss
FROM parts p
INNER JOIN inspections i ON p.part_code = i.part_code
GROUP BY p.part_code, p.part_name, p.category, p.unit_price
ORDER BY defect_loss DESC
───────────────────────────────────────────────
shape: (5, 10)
┌───────────┬────────────┬────────────┬───────────┬───┬───────────┬────────┬───────────┬───────────┐
│ part_code ┆ part_name ┆ category ┆ unit_pric ┆ … ┆ total_def ┆ dr_pct ┆ productio ┆ defect_lo │
│ --- ┆ --- ┆ --- ┆ e ┆ ┆ ect ┆ --- ┆ n_value ┆ ss │
│ str ┆ str ┆ str ┆ --- ┆ ┆ --- ┆ f64 ┆ --- ┆ --- │
│ ┆ ┆ ┆ i64 ┆ ┆ i64 ┆ ┆ i64 ┆ i64 │
╞═══════════╪════════════╪════════════╪═══════════╪═══╪═══════════╪════════╪═══════════╪═══════════╡
│ ENG-002 ┆ Crankshaft ┆ Engine ┆ 8500 ┆ … ┆ 78 ┆ 2.25 ┆ 29461000 ┆ 663000 │
│ ┆ ┆ parts ┆ ┆ ┆ ┆ ┆ ┆ │
│ ELC-001 ┆ Alternator ┆ electrical ┆ 6800 ┆ … ┆ 59 ┆ 2.96 ┆ 13545600 ┆ 401200 │
│ ┆ ┆ components ┆ ┆ ┆ ┆ ┆ ┆ │
│ ENG-001 ┆ piston ┆ Engine ┆ 1200 ┆ … ┆ 159 ┆ 1.9 ┆ 10047600 ┆ 190800 │
│ ┆ ring ┆ parts ┆ ┆ ┆ ┆ ┆ ┆ │
│ BRK-001 ┆ brake pad ┆ brake ┆ 950 ┆ … ┆ 116 ┆ 1.99 ┆ 5547050 ┆ 110200 │
│ ┆ ┆ parts ┆ ┆ ┆ ┆ ┆ ┆ │
│ SUS-001 ┆ shock ┆ suspension ┆ 2800 ┆ … ┆ 35 ┆ 2.46 ┆ 3981600 ┆ 98000 │
│ ┆ absorber ┆ ┆ ┆ ┆ ┆ ┆ ┆ │
└───────────┴────────────┴────────────┴───────────┴───┴───────────┴────────┴───────────┴───────────┘
↳ 5 rows retrieved
| part_code | part_name | category | unit_price | n_records | total_prod | total_defect | dr_pct | production_value | defect_loss |
|---|---|---|---|---|---|---|---|---|---|
| str | str | str | i64 | i64 | i64 | i64 | f64 | i64 | i64 |
| "ENG-002" | "Crankshaft" | "Engine parts" | 8500 | 10 | 3466 | 78 | 2.25 | 29461000 | 663000 |
| "ELC-001" | "Alternator" | "electrical components" | 6800 | 10 | 1992 | 59 | 2.96 | 13545600 | 401200 |
| "ENG-001" | "piston ring" | "Engine parts" | 1200 | 20 | 8373 | 159 | 1.9 | 10047600 | 190800 |
| "BRK-001" | "brake pad" | "brake parts" | 950 | 20 | 5839 | 116 | 1.99 | 5547050 | 110200 |
| "SUS-001" | "shock absorber" | "suspension" | 2800 | 10 | 1422 | 35 | 2.46 | 3981600 | 98000 |
Interpreting the results
defect_lossthe top parts (defect loss amount) are the Top Priority Target for improvement investments. High-priced parts (ENG-002: ¥8,500 / ELC-001: ¥6,800) Even if the number of defects is small, the loss amount can be large- The three parts, BRK-002 / ELC-002 / SUS-002, do not have matching rows in the inspections, Not displayed. the results of INNER JOIN. (The left side is ‘parts’, so you can display it with LEFT JOIN)
- If the “Defect Ranking” and “Loss Amount Ranking” differ, By prioritizing based on loss amounts, you can accurately assess Operational Impact
No.046: Joining Multiple Tables
Practical use
Joining the factory, line, part, and inspection tables lets one query compare defect rates by factory, line, and part.
Examples of use in manufacturing:
- Generation of data for multi-axis KPI dashboards for management meetings
- Cross-tabulation of factory × line × parts categories
- Automatically assigning line names and capacity information to performance data
How the SQL works
JOIN for multiple tables is written with the order of joins in mind.
FROM inspections i
INNER JOIN factories f ON i.factory_id = f.factory_id
INNER JOIN lines l ON i.line_code = l.line_code
INNER JOIN parts p ON i.part_code = p.part_code
The database engine optimizes the execution order, The join order prioritizes the query’s intent (the table you want to narrow down first).
Run in Python
# No.046: 4-Table INNER JOIN — Factory × Line × Parts KPI Aggregation
print('=== 4Table joining: Factory × Line × Parts Category Aggregate ===')
q(conn, '''
SELECT f.factory_name,
f.region,
l.line_name,
p.part_name,
p.category,
COUNT(i.id) AS n_records,
SUM(i.production_qty) AS total_prod,
SUM(i.defect_qty) AS total_defect,
ROUND(SUM(i.defect_qty) * 100.0 / SUM(i.production_qty), 2) AS dr_pct
FROM inspections i
INNER JOIN factories f ON i.factory_id = f.factory_id
INNER JOIN lines l ON i.line_code = l.line_code
INNER JOIN parts p ON i.part_code = p.part_code
GROUP BY f.factory_id, l.line_code, p.part_code
ORDER BY f.factory_id, dr_pct DESC
''')
=== 4Table joining: Factory × Line × Parts Category Aggregate ===
── SQL ─────────────────────────────────────────
SELECT f.factory_name,
f.region,
l.line_name,
p.part_name,
p.category,
COUNT(i.id) AS n_records,
SUM(i.production_qty) AS total_prod,
SUM(i.defect_qty) AS total_defect,
ROUND(SUM(i.defect_qty) * 100.0 / SUM(i.production_qty), 2) AS dr_pct
FROM inspections i
INNER JOIN factories f ON i.factory_id = f.factory_id
INNER JOIN lines l ON i.line_code = l.line_code
INNER JOIN parts p ON i.part_code = p.part_code
GROUP BY f.factory_id, l.line_code, p.part_code
ORDER BY f.factory_id, dr_pct DESC
───────────────────────────────────────────────
shape: (7, 9)
┌────────────┬────────────┬───────────┬───────────┬───┬───────────┬───────────┬───────────┬────────┐
│ factory_na ┆ region ┆ line_name ┆ part_name ┆ … ┆ n_records ┆ total_pro ┆ total_def ┆ dr_pct │
│ me ┆ --- ┆ --- ┆ --- ┆ ┆ --- ┆ d ┆ ect ┆ --- │
│ --- ┆ str ┆ str ┆ str ┆ ┆ i64 ┆ --- ┆ --- ┆ f64 │
│ str ┆ ┆ ┆ ┆ ┆ ┆ i64 ┆ i64 ┆ │
╞════════════╪════════════╪═══════════╪═══════════╪═══╪═══════════╪═══════════╪═══════════╪════════╡
│ Tokyo ┆ Kanto ┆ Engine ┆ piston ┆ … ┆ 10 ┆ 4582 ┆ 90 ┆ 1.96 │
│ Factory ┆ ┆ parts ┆ ring ┆ ┆ ┆ ┆ ┆ │
│ ┆ ┆ line ┆ ┆ ┆ ┆ ┆ ┆ │
│ Tokyo ┆ Kanto ┆ Brake ┆ brake pad ┆ … ┆ 10 ┆ 3014 ┆ 59 ┆ 1.96 │
│ Factory ┆ ┆ Parts ┆ ┆ ┆ ┆ ┆ ┆ │
│ ┆ ┆ Line ┆ ┆ ┆ ┆ ┆ ┆ │
│ Osaka ┆ Kansai ┆ Electrica ┆ Alternato ┆ … ┆ 10 ┆ 1992 ┆ 59 ┆ 2.96 │
│ Factory ┆ ┆ l Compone ┆ r ┆ ┆ ┆ ┆ ┆ │
│ ┆ ┆ nts Line ┆ ┆ ┆ ┆ ┆ ┆ │
│ Osaka ┆ Kansai ┆ Engine ┆ piston ┆ … ┆ 10 ┆ 3791 ┆ 69 ┆ 1.82 │
│ Factory ┆ ┆ parts ┆ ring ┆ ┆ ┆ ┆ ┆ │
│ ┆ ┆ line ┆ ┆ ┆ ┆ ┆ ┆ │
│ Nagoya ┆ Central ┆ Suspensio ┆ shock ┆ … ┆ 10 ┆ 1422 ┆ 35 ┆ 2.46 │
│ Factory ┆ region ┆ n line ┆ absorber ┆ ┆ ┆ ┆ ┆ │
│ Nagoya ┆ Central ┆ Brake ┆ brake pad ┆ … ┆ 10 ┆ 2825 ┆ 57 ┆ 2.02 │
│ Factory ┆ region ┆ Parts ┆ ┆ ┆ ┆ ┆ ┆ │
│ ┆ ┆ Line ┆ ┆ ┆ ┆ ┆ ┆ │
│ Fukuoka ┆ Kyushu ┆ Engine ┆ Crankshaf ┆ … ┆ 10 ┆ 3466 ┆ 78 ┆ 2.25 │
│ Factory ┆ ┆ parts ┆ t ┆ ┆ ┆ ┆ ┆ │
│ ┆ ┆ line ┆ ┆ ┆ ┆ ┆ ┆ │
└────────────┴────────────┴───────────┴───────────┴───┴───────────┴───────────┴───────────┴────────┘
↳ 7 rows retrieved
| factory_name | region | line_name | part_name | category | n_records | total_prod | total_defect | dr_pct |
|---|---|---|---|---|---|---|---|---|
| str | str | str | str | str | i64 | i64 | i64 | f64 |
| "Tokyo Factory" | "Kanto" | "Engine parts line" | "piston ring" | "Engine parts" | 10 | 4582 | 90 | 1.96 |
| "Tokyo Factory" | "Kanto" | "Brake Parts Line" | "brake pad" | "brake parts" | 10 | 3014 | 59 | 1.96 |
| "Osaka Factory" | "Kansai" | "Electrical Components Line" | "Alternator" | "electrical components" | 10 | 1992 | 59 | 2.96 |
| "Osaka Factory" | "Kansai" | "Engine parts line" | "piston ring" | "Engine parts" | 10 | 3791 | 69 | 1.82 |
| "Nagoya Factory" | "Central region" | "Suspension line" | "shock absorber" | "suspension" | 10 | 1422 | 35 | 2.46 |
| "Nagoya Factory" | "Central region" | "Brake Parts Line" | "brake pad" | "brake parts" | 10 | 2825 | 57 | 2.02 |
| "Fukuoka Factory" | "Kyushu" | "Engine parts line" | "Crankshaft" | "Engine parts" | 10 | 3466 | 78 | 2.25 |
Interpreting the results
- Four tables were combined, and factory name / region / line name / part name / category was assigned A highly readable summary can be generated in a single query.
- Defect rates differ by line. Each line has ten records, but product mix and production volumes differ. Equal record counts do not ensure comparability; compare similar conditions before attributing differences to processes or equipment.
No.047: Pay attention to duplicate binding keys
Practical use
If the same key is exist multiple in the target table, The number of rows after merging increases compared to expected (fan-out).
Typical examples in manufacturing:
- If the quality standards table is operated as the ‘Standard Revision History,’ There are two lines in the same part code: “Standard Standard (2024Q1)” and “Strict Standard (2024Q2)”.
- When you JOIN the part master to this quality standard table, you Increase in line count
How the SQL works
Four parts in quality_specs each have two rows: a standard and a stricter specification.
| parts Number of lines | After INNER JOIN, | Reasons for the increase |
|---|---|---|
| 8 lines | 11 lines | ENG-001/002, BRK-001, ELC-001 each fan-out on two lines |
Here, and are the number of times key appears at each table.
Run in Python
# No.047: Duplicate Combine Keys — Confirmed Increase in Line Count in parts × quality_specs
print('=== parts(8Item)× quality_specs(11Item) INNER JOIN ===')
q(conn, '''
SELECT p.part_code,
p.part_name,
p.unit_price,
qs.spec_type,
qs.max_dr_pct,
qs.effective_from
FROM parts p
INNER JOIN quality_specs qs ON p.part_code = qs.part_code
ORDER BY p.part_code, qs.effective_from
''')
print()
print('=== Which parts meet which standards (checking for duplicates)===')
q(conn, '''
SELECT p.part_code,
p.part_name,
COUNT(qs.spec_id) AS spec_count
FROM parts p
LEFT JOIN quality_specs qs ON p.part_code = qs.part_code
GROUP BY p.part_code, p.part_name
ORDER BY spec_count DESC, p.part_code
''')
=== parts(8Item)× quality_specs(11Item) INNER JOIN ===
── SQL ─────────────────────────────────────────
SELECT p.part_code,
p.part_name,
p.unit_price,
qs.spec_type,
qs.max_dr_pct,
qs.effective_from
FROM parts p
INNER JOIN quality_specs qs ON p.part_code = qs.part_code
ORDER BY p.part_code, qs.effective_from
───────────────────────────────────────────────
shape: (11, 6)
┌───────────┬────────────────┬────────────┬───────────────────┬────────────┬────────────────┐
│ part_code ┆ part_name ┆ unit_price ┆ spec_type ┆ max_dr_pct ┆ effective_from │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ str ┆ i64 ┆ str ┆ f64 ┆ str │
╞═══════════╪════════════════╪════════════╪═══════════════════╪════════════╪════════════════╡
│ BRK-001 ┆ brake pad ┆ 950 ┆ standard standard ┆ 2.5 ┆ 2024-01-01 │
│ BRK-001 ┆ brake pad ┆ 950 ┆ Strict standards ┆ 2.0 ┆ 2024-03-01 │
│ BRK-002 ┆ brake caliper ┆ 4200 ┆ standard standard ┆ 3.0 ┆ 2024-01-01 │
│ ELC-001 ┆ Alternator ┆ 6800 ┆ standard standard ┆ 3.5 ┆ 2024-01-01 │
│ ELC-001 ┆ Alternator ┆ 6800 ┆ Strict standards ┆ 3.0 ┆ 2024-03-01 │
│ … ┆ … ┆ … ┆ … ┆ … ┆ … │
│ ENG-001 ┆ piston ring ┆ 1200 ┆ standard standard ┆ 2.0 ┆ 2024-01-01 │
│ ENG-001 ┆ piston ring ┆ 1200 ┆ Strict standards ┆ 1.5 ┆ 2024-03-01 │
│ ENG-002 ┆ Crankshaft ┆ 8500 ┆ standard standard ┆ 1.8 ┆ 2024-01-01 │
│ ENG-002 ┆ Crankshaft ┆ 8500 ┆ Strict standards ┆ 1.2 ┆ 2024-03-01 │
│ SUS-001 ┆ shock absorber ┆ 2800 ┆ standard standard ┆ 2.8 ┆ 2024-01-01 │
└───────────┴────────────────┴────────────┴───────────────────┴────────────┴────────────────┘
↳ 11 rows retrieved
=== Which parts meet which standards (checking for duplicates)===
── SQL ─────────────────────────────────────────
SELECT p.part_code,
p.part_name,
COUNT(qs.spec_id) AS spec_count
FROM parts p
LEFT JOIN quality_specs qs ON p.part_code = qs.part_code
GROUP BY p.part_code, p.part_name
ORDER BY spec_count DESC, p.part_code
───────────────────────────────────────────────
shape: (8, 3)
┌───────────┬────────────────┬────────────┐
│ part_code ┆ part_name ┆ spec_count │
│ --- ┆ --- ┆ --- │
│ str ┆ str ┆ i64 │
╞═══════════╪════════════════╪════════════╡
│ BRK-001 ┆ brake pad ┆ 2 │
│ ELC-001 ┆ Alternator ┆ 2 │
│ ENG-001 ┆ piston ring ┆ 2 │
│ ENG-002 ┆ Crankshaft ┆ 2 │
│ BRK-002 ┆ brake caliper ┆ 1 │
│ ELC-002 ┆ Starter motor ┆ 1 │
│ SUS-001 ┆ shock absorber ┆ 1 │
│ SUS-002 ┆ coil spring ┆ 0 │
└───────────┴────────────────┴────────────┘
↳ 8 rows retrieved
| part_code | part_name | spec_count |
|---|---|---|
| str | str | i64 |
| "BRK-001" | "brake pad" | 2 |
| "ELC-001" | "Alternator" | 2 |
| "ENG-001" | "piston ring" | 2 |
| "ENG-002" | "Crankshaft" | 2 |
| "BRK-002" | "brake caliper" | 1 |
| "ELC-002" | "Starter motor" | 1 |
| "SUS-001" | "shock absorber" | 1 |
| "SUS-002" | "coil spring" | 0 |
Interpreting the results
- If you INNER JOIN
parts(8 items) andquality_specs(11 items), you get 11records. This is because parts for ENG-001, ENG-002, BRK-001, and ELC-001 each have two rows (standard and strict standards) - SUS-002 is excluded from INNER JOIN due to lack of
quality_specsstandards (line 1 → line 0). - To use the latest specification, find the maximum
effective_fromper part and restrict the specification rows before joining. If multiple specifications share that date, define an additional tie-breaker.
No.048: Confirm an increase in the number of cases after merging
Practical use
After executing JOIN, Habit of checking if the number of cases meets expectations This is the foundation of data engineering.
Importance in Manufacturing:
- If you calculate SUM without noticing the increase in row count in aggregate queries, a double counting occurs.
- When monthly report values suddenly increase, it is often caused by duplicate JOIN keys.
- Ensuring quality by asserting
COUNT(*)in CI/CD pipelines
How the SQL works
Steps to check the number of cases before and after JOIN:
- Number of cases before merging:
SELECT COUNT(*) FROM parts→ 8 - After INNER JOIN:
SELECT COUNT(*) FROM parts INNER JOIN quality_specs ...→ 11 cases (increase) - After LEFT JOIN:
SELECT COUNT(*) FROM parts LEFT JOIN quality_specs ...→ 12 records (including the NULL line in SUS-002) - Identifying duplicate keys:
GROUP BY key HAVING COUNT(*) > 1
Run in Python
# No.048: Gradually Confirm the Increase in the Number of Cases After Joining
parts_n = conn.execute('SELECT COUNT(*) FROM parts').fetchone()[0]
qs_n = conn.execute('SELECT COUNT(*) FROM quality_specs').fetchone()[0]
inner_n = conn.execute('''
SELECT COUNT(*) FROM parts
INNER JOIN quality_specs ON parts.part_code = quality_specs.part_code
''').fetchone()[0]
left_n = conn.execute('''
SELECT COUNT(*) FROM parts
LEFT JOIN quality_specs ON parts.part_code = quality_specs.part_code
''').fetchone()[0]
print('=== JOIN Comparison of the number of cases before and after ===')
print(f' parts : {parts_n} records')
print(f' quality_specs : {qs_n} records')
print(f' INNER JOIN After : {inner_n} records ← parts More {inner_n - parts_n} Increase in cases (duplicate keys)')
print(f' LEFT JOIN After : {left_n} records ← INNER More {left_n - inner_n} Increase in cases (NULL rows: SUS-002)')
# Identify parts with duplicate keys in quality_specs
print()
print('=== quality_specs Duplicate within part_code ===')
q(conn, '''
SELECT part_code, COUNT(*) AS spec_count
FROM quality_specs
GROUP BY part_code
HAVING COUNT(*) > 1
ORDER BY spec_count DESC, part_code
''')
=== JOIN Comparison of the number of cases before and after ===
parts : 8 records
quality_specs : 11 records
INNER JOIN After : 11 records ← parts More 3 Increase in cases (duplicate keys)
LEFT JOIN After : 12 records ← INNER More 1 Increase in cases (NULL rows: SUS-002)
=== quality_specs Duplicate within part_code ===
── SQL ─────────────────────────────────────────
SELECT part_code, COUNT(*) AS spec_count
FROM quality_specs
GROUP BY part_code
HAVING COUNT(*) > 1
ORDER BY spec_count DESC, part_code
───────────────────────────────────────────────
shape: (4, 2)
┌───────────┬────────────┐
│ part_code ┆ spec_count │
│ --- ┆ --- │
│ str ┆ i64 │
╞═══════════╪════════════╡
│ BRK-001 ┆ 2 │
│ ELC-001 ┆ 2 │
│ ENG-001 ┆ 2 │
│ ENG-002 ┆ 2 │
└───────────┴────────────┘
↳ 4 rows retrieved
| part_code | spec_count |
|---|---|
| str | i64 |
| "BRK-001" | 2 |
| "ELC-001" | 2 |
| "ENG-001" | 2 |
| "ENG-002" | 2 |
Interpreting the results
INNER JOINAfter that, the number of parts items increased from 8 to 11.quality_specsThe cause is four components (ENG-001/002, BRK-001, ELC-001) that have duplicate keysLEFT JOINAfter that, one more case increased, bringing the total to 12. SUS-002 will be added as a NULL line- Countermeasures: After JOIN, check the number of
COUNT(*)and if there is any unintended increase,GROUP BY ... HAVING COUNT(*) > 1Identify duplicate keys - Make it a habit to always check the number of entries before running aggregated queries (SUM / AVG)
No.049: Extracting Parts Without Inspection Records
Practical use
LEFT JOIN + WHERE IS NULL Patterns “Detecting what doesn’t exist”
It is one of the most powerful SQL techniques.
Examples of use in manufacturing:
- Although it is registered in the parts master, this fiscal year the parts are produced at zero (discontinued?) Missed the proper planning?)
- Parts not registered with quality standards (risk management gaps)
- On days when the performance hasn’t arrived from a line that should be operating (sensor abnormality?) Data integration error?)
How the SQL works
SELECT p.*
FROM parts p
LEFT JOIN inspections i ON p.part_code = i.part_code
WHERE i.id IS NULL -- ← Only rows with no match in the right table
WHERE i.id IS NULL extracts “NULL lines in LEFT JOIN = unrecorded parts.”
Run in Python
# No.049: Extracting parts without inspection experience using LEFT JOIN + WHERE IS NULL
# (1) Number of inspections for all items (LEFT JOIN + GROUP BY)
print('=== ① Number of inspections for all products (LEFT JOIN Zero parts are also displayed.)===')
df_parts_join = q(conn, '''
SELECT p.part_code,
p.part_name,
p.category,
p.unit_price,
COUNT(i.id) AS inspection_count
FROM parts p
LEFT JOIN inspections i ON p.part_code = i.part_code
GROUP BY p.part_code, p.part_name, p.category, p.unit_price
ORDER BY p.part_code
''')
print()
print('=== ② Only parts without inspection records (WHERE i.id IS NULL)===')
q(conn, '''
SELECT p.part_code,
p.part_name,
p.category,
p.unit_price,
p.supplier_code
FROM parts p
LEFT JOIN inspections i ON p.part_code = i.part_code
WHERE i.id IS NULL
ORDER BY p.part_code
''')
=== ① Number of inspections for all products (LEFT JOIN Zero parts are also displayed.)===
── SQL ─────────────────────────────────────────
SELECT p.part_code,
p.part_name,
p.category,
p.unit_price,
COUNT(i.id) AS inspection_count
FROM parts p
LEFT JOIN inspections i ON p.part_code = i.part_code
GROUP BY p.part_code, p.part_name, p.category, p.unit_price
ORDER BY p.part_code
───────────────────────────────────────────────
shape: (8, 5)
┌───────────┬────────────────┬───────────────────────┬────────────┬──────────────────┐
│ part_code ┆ part_name ┆ category ┆ unit_price ┆ inspection_count │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ str ┆ str ┆ i64 ┆ i64 │
╞═══════════╪════════════════╪═══════════════════════╪════════════╪══════════════════╡
│ BRK-001 ┆ brake pad ┆ brake parts ┆ 950 ┆ 20 │
│ BRK-002 ┆ brake caliper ┆ brake parts ┆ 4200 ┆ 0 │
│ ELC-001 ┆ Alternator ┆ electrical components ┆ 6800 ┆ 10 │
│ ELC-002 ┆ Starter motor ┆ electrical components ┆ 3500 ┆ 0 │
│ ENG-001 ┆ piston ring ┆ Engine parts ┆ 1200 ┆ 20 │
│ ENG-002 ┆ Crankshaft ┆ Engine parts ┆ 8500 ┆ 10 │
│ SUS-001 ┆ shock absorber ┆ suspension ┆ 2800 ┆ 10 │
│ SUS-002 ┆ coil spring ┆ suspension ┆ 1800 ┆ 0 │
└───────────┴────────────────┴───────────────────────┴────────────┴──────────────────┘
↳ 8 rows retrieved
=== ② Only parts without inspection records (WHERE i.id IS NULL)===
── SQL ─────────────────────────────────────────
SELECT p.part_code,
p.part_name,
p.category,
p.unit_price,
p.supplier_code
FROM parts p
LEFT JOIN inspections i ON p.part_code = i.part_code
WHERE i.id IS NULL
ORDER BY p.part_code
───────────────────────────────────────────────
shape: (3, 5)
┌───────────┬───────────────┬───────────────────────┬────────────┬───────────────┐
│ part_code ┆ part_name ┆ category ┆ unit_price ┆ supplier_code │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ str ┆ str ┆ i64 ┆ str │
╞═══════════╪═══════════════╪═══════════════════════╪════════════╪═══════════════╡
│ BRK-002 ┆ brake caliper ┆ brake parts ┆ 4200 ┆ SUP-02 │
│ ELC-002 ┆ Starter motor ┆ electrical components ┆ 3500 ┆ SUP-03 │
│ SUS-002 ┆ coil spring ┆ suspension ┆ 1800 ┆ SUP-04 │
└───────────┴───────────────┴───────────────────────┴────────────┴───────────────┘
↳ 3 rows retrieved
| part_code | part_name | category | unit_price | supplier_code |
|---|---|---|---|---|
| str | str | str | i64 | str |
| "BRK-002" | "brake caliper" | "brake parts" | 4200 | "SUP-02" |
| "ELC-002" | "Starter motor" | "electrical components" | 3500 | "SUP-03" |
| "SUS-002" | "coil spring" | "suspension" | 1800 | "SUP-04" |
# No.049 Visualization: Number of Inspections by Part (Highlight Uninspected Parts in Red)
rows_p = df_parts_join.to_dicts()
p_codes = [r['part_code'] for r in rows_p]
counts = [r['inspection_count'] for r in rows_p]
bar_col = ['#D65F5F' if c == 0 else '#4878CF' for c in counts]
fig, ax = plt.subplots(figsize=(10, 5))
bars = ax.bar(range(len(p_codes)), counts, color=bar_col, alpha=0.85,
edgecolor='black', linewidth=0.4)
for bar, v in zip(bars, counts):
ax.text(bar.get_x() + bar.get_width() / 2, bar.get_height() + 0.3,
str(v), ha='center', va='bottom', fontsize=9)
ax.set_xticks(range(len(p_codes)))
ax.set_xticklabels(p_codes, rotation=30, ha='right', fontsize=9)
ax.set_title('By Component Number of Tests (LEFT JOINCovers all items here)', fontsize=12, pad=10)
ax.set_xlabel('Part code', fontsize=10)
ax.set_ylabel('Number of Tests', fontsize=10)
ax.grid(axis='y', alpha=0.3)
legend_h = [
Patch(color='#4878CF', alpha=0.85, label='Inspection track record'),
Patch(color='#D65F5F', alpha=0.85, label='No inspection record (please confirm)'),
]
ax.legend(handles=legend_h, fontsize=9, loc='upper right')
plt.tight_layout()
plt.show()
print('Completion of Display of Inspection Count Graph by Part (SVG 2/2)')
Completion of Display of Inspection Count Graph by Part (SVG 2/2)
Interpreting the results
- BRK-002 / ELC-002 / SUS-002 three parts will appear as zero inspection counts (red bar). Just by looking at the graph, you can instantly grasp the list of parts not inspected this fiscal year
- These parts may not be allocated to this season’s lineup. This triggers the site to confirm whether production has been discontinued, is the setup being changed, or if there is a data linkage missing.
LEFT JOIN ... WHERE i.id IS NULLis an anti-join pattern.NOT EXISTSis another way to express the same test.NOT INbehaves differently when its list contains NULL, so check nullability before using it.
No.050: Detecting inspection records missing in the component master
Practical use
This is the reverse pattern of No.049. This time “There is no master code to reference for the achievement data.” = Detects Isolated (Orphant) Records.
Examples of use in manufacturing:
- Manual input errors or inspection records registered with old codes (such as UNKNOWN-999)
- Achievement data remaining after master deletion (lack of deletion protection)
- Unknown code slipped in due to data integration errors from external systems
How the SQL works
SELECT i.*
FROM inspections i
LEFT JOIN parts p ON i.part_code = p.part_code
WHERE p.part_code IS NULL -- ← parts There was no agreement = invalid part code
It’s the same LEFT JOIN + WHERE IS NULL pattern as No.049,
Pay attention to JOINThe direction (which is the reference) is reversed. things.
Run in Python
# No.050: Detection of Inspection Records (Invalid part_code) Not Present in the Component Master
print('=== fraud part_code detection (LEFT JOIN + WHERE p.part_code IS NULL)===')
q(conn, '''
SELECT i.id,
i.inspection_date,
i.factory_id,
i.line_code,
i.part_code AS orphaned_part_code,
i.shift,
i.production_qty,
i.defect_qty,
p.part_name AS part_name_check
FROM inspections i
LEFT JOIN parts p ON i.part_code = p.part_code
WHERE p.part_code IS NULL
ORDER BY i.id
''')
print()
print('=== Aggregation of invalid part codes (which factory or line they came from)===')
q(conn, '''
SELECT i.factory_id, i.line_code,
COUNT(*) AS orphaned_count,
i.part_code AS orphaned_code
FROM inspections i
LEFT JOIN parts p ON i.part_code = p.part_code
WHERE p.part_code IS NULL
GROUP BY i.factory_id, i.line_code, i.part_code
ORDER BY orphaned_count DESC
''')
=== fraud part_code detection (LEFT JOIN + WHERE p.part_code IS NULL)===
── SQL ─────────────────────────────────────────
SELECT i.id,
i.inspection_date,
i.factory_id,
i.line_code,
i.part_code AS orphaned_part_code,
i.shift,
i.production_qty,
i.defect_qty,
p.part_name AS part_name_check
FROM inspections i
LEFT JOIN parts p ON i.part_code = p.part_code
WHERE p.part_code IS NULL
ORDER BY i.id
───────────────────────────────────────────────
shape: (3, 9)
┌─────┬─────────────┬─────────────┬───────────┬───┬───────┬─────────────┬─────────────┬────────────┐
│ id ┆ inspection_ ┆ factory_id ┆ line_code ┆ … ┆ shift ┆ production_ ┆ defect_qty ┆ part_name_ │
│ --- ┆ date ┆ --- ┆ --- ┆ ┆ --- ┆ qty ┆ --- ┆ check │
│ i64 ┆ --- ┆ str ┆ str ┆ ┆ str ┆ --- ┆ i64 ┆ --- │
│ ┆ str ┆ ┆ ┆ ┆ ┆ i64 ┆ ┆ null │
╞═════╪═════════════╪═════════════╪═══════════╪═══╪═══════╪═════════════╪═════════════╪════════════╡
│ 71 ┆ 2024-01-15 ┆ F01 ┆ LINE-A1 ┆ … ┆ early ┆ 450 ┆ 8 ┆ null │
│ ┆ ┆ ┆ ┆ ┆ shift ┆ ┆ ┆ │
│ 72 ┆ 2024-01-22 ┆ F02 ┆ LINE-B1 ┆ … ┆ late ┆ 375 ┆ 12 ┆ null │
│ ┆ ┆ ┆ ┆ ┆ shift ┆ ┆ ┆ │
│ 73 ┆ 2024-02-10 ┆ F03 ┆ LINE-C1 ┆ … ┆ early ┆ 148 ┆ 9 ┆ null │
│ ┆ ┆ ┆ ┆ ┆ shift ┆ ┆ ┆ │
└─────┴─────────────┴─────────────┴───────────┴───┴───────┴─────────────┴─────────────┴────────────┘
↳ 3 rows retrieved
=== Aggregation of invalid part codes (which factory or line they came from)===
── SQL ─────────────────────────────────────────
SELECT i.factory_id, i.line_code,
COUNT(*) AS orphaned_count,
i.part_code AS orphaned_code
FROM inspections i
LEFT JOIN parts p ON i.part_code = p.part_code
WHERE p.part_code IS NULL
GROUP BY i.factory_id, i.line_code, i.part_code
ORDER BY orphaned_count DESC
───────────────────────────────────────────────
shape: (3, 4)
┌────────────┬───────────┬────────────────┬───────────────┐
│ factory_id ┆ line_code ┆ orphaned_count ┆ orphaned_code │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ str ┆ i64 ┆ str │
╞════════════╪═══════════╪════════════════╪═══════════════╡
│ F01 ┆ LINE-A1 ┆ 1 ┆ UNKNOWN-999 │
│ F02 ┆ LINE-B1 ┆ 1 ┆ UNKNOWN-999 │
│ F03 ┆ LINE-C1 ┆ 1 ┆ UNKNOWN-999 │
└────────────┴───────────┴────────────────┴───────────────┘
↳ 3 rows retrieved
| factory_id | line_code | orphaned_count | orphaned_code |
|---|---|---|---|
| str | str | i64 | str |
| "F01" | "LINE-A1" | 1 | "UNKNOWN-999" |
| "F02" | "LINE-B1" | 1 | "UNKNOWN-999" |
| "F03" | "LINE-C1" | 1 | "UNKNOWN-999" |
Interpreting the results
- Three cases of
part_code = 'UNKNOWN-999'were detected.part_name_checkisNULL. These are records with invalid codes that do not exist in thepartsmaster - The invalid code appears in factories F01, F02, and F03. Check entry history and integration logs to distinguish manual input, code changes, and integration errors. Its distribution alone does not identify the cause.
- Response Procedure:
orphaned_countContact data managers at factories and lines with high levels of- Identify the correct
part_codeand fix it with UPDATE or DELETE - Adding foreign key constraints (
FOREIGN KEY) to prevent recurrence
LEFT JOIN + WHERE IS NULLPattern as a practical Data Quality Check Query It is effective when incorporated into regular execution (cron / Airflow)
Applying these queries at work
Through JOIN taught in No.041–050, the following manufacturing practical challenges can be solved using SQL.
| Practical Issues | SQL Patterns |
|---|---|
| Factory name and region added to the track record | INNER JOIN factories |
| Unit price × Calculate loss amount based on number of defects | INNER JOIN parts + SUM(defect * price) |
| Include factories with no inspections | FROM factories f LEFT JOIN inspections i ON ... + COALESCE(...) |
| Cross-table KPIs of 3 or more tables | JOIN factories JOIN lines JOIN parts |
| Prevention of miscalculations due to overlapping quality standards | Check COUNT(*) before and after JOIN |
| Identification of uninspected parts and unoperated lines | LEFT JOIN ... WHERE IS NULL |
| Detecting and correcting invalid part codes | LEFT JOIN parts ... WHERE p.part_code IS NULL |
Saving the JOIN conditions lets you repeat the matching each month without rebuilding VLOOKUP ranges.
Steps for practical use
1. Establishment of foreign key constraints
In SQLite, check PRAGMA foreign_keys on each connection and enable enforcement with PRAGMA foreign_keys = ON; before starting a transaction. Define suitable FOREIGN KEY constraints in the production database to reject part codes absent from the master table.
2. Index Settings
Join keys such as factory_id, part_code, and line_code are candidates for indexes. Check existing indexes, filtering conditions, the query plan, and measured runtime before deciding to add one.
CREATE INDEX idx_insp_part ON inspections(part_code);
3. Regular execution of LEFT JOIN + WHERE IS NULL
Run the data quality checks from No.049 and No.050 on a schedule, and alert the responsible team when invalid part codes or uninspected parts are found.
4. Assertions of the number of cases after JOIN combination
In ETL pipelines or monthly aggregation batches, you can add assertions using COUNT(*),
We recommend designing a system that suspends processing or issues alerts when the expected number of cases is exceeded.
Conclusion
In this chapter, we used SQL JOIN to analyze multiple tables in the manufacturing performance database.
| exercise | Main SQL | Key Points for Use in Manufacturing |
|---|---|---|
| No.041 | INNER JOIN | Basic Combination with Factory Name and Unit Price Added to Performance |
| No.042 | LEFT JOIN | Identifying factories with zero inspection records based on a whole-factory standard |
| No.043 | RIGHT JOIN | Understanding the Equivalence with LEFT JOIN |
| No.044 | JOIN factories | KPI (Defect Rate/Occupancy Rate) Aggregation by Factory |
| No.045 | JOIN parts | Loss Ranking by Part |
| No.046 | JOIN × 3 chain | Cross-section analysis of factory + line + parts + inspection records |
| No.047 | Identifying duplicate keys | Increase in the number of rows due to duplicate quality standards tables |
| No.048 | Number of Assertions | Quality assurance through COUNT(*) before and after JOIN |
| No.049 | LEFT JOIN + WHERE IS NULL | Automatic identification of uninspected parts |
| No.050 | LEFT JOIN + WHERE IS NULL | Automatic detection of invalid part code |
In the next chapter (Chapter 6: Subqueries and CTE), Learn how to build even more complex analytical queries in combination with JOIN.
Consulting for businesses
Please feel free to consult us about data analysis, SQL education, and DX promotion in manufacturing using the information below.
📩 Contact Us: www.surikobo.co.jp/contact Please feel free to consult us first.