All articles →

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

SceneCurrent ChallengesWhat SQL JOIN can solve
Summary of Results by FactoryFactory code → Factory name conversion manually done with VLOOKUPAutomatically assign factory names to INNER JOIN factories
Calculation of Loss Amount for PartsManage unit price tables and performance tables separatelyJOIN parts Combine unit prices to calculate the loss amount
Identification of Uninspected PartsManually check by comparing the master and achievementsAutomatic extraction with LEFT JOIN ... WHERE IS NULL
Detecting Malicious CodeVisually check whether the code for the achievement data exists in the masterAutomatic detection by LEFT JOIN ... WHERE IS NULL
Joining three or more tablesCombining multiple VLOOKUPs to complicateChain 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.TitlesApplications in manufacturing
041Join tables with INNER JOINInspection Records × Basic Integration of Factory Masters
042Join one table based on LEFT JOINIdentifying factories with zero inspection records based on all factories
043Understanding the RIGHT JOIN ConceptUnderstanding the equivalence relationship with LEFT JOIN
044Integrating factory master and inspection recordsAggregation of Results with Factory Name and Regional Information
045Combining the part master with inspection recordsCalculation of loss amount with unit price information attached
046Join multiple tablesFour-table cross-table analysis: factory + line + parts + inspection records
047Pay attention to duplicate binding keysTracking Increase in Number of Rows Due to Duplicate Quality Standards Tables
048Confirm the increase in the number of cases after mergingEnsuring data quality through verification of number of transactions before and after JOIN
049Extracting parts without inspection recordsIdentifying uninspected parts and prioritizing master maintenance
050Detecting inspection records that do not exist in the component masterDetection 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.

[IN: 1]
import platform

print(f"OS: {platform.system()} {platform.release()}")
print(f"Python: {platform.python_version()}")
[OUT: 1]
OS: Darwin 25.5.0
Python: 3.14.4
[IN: 2]
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")
[OUT: 2]
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 Namenumber of casesDescription
factories5 itemsFactory master (F05: Sendai Factory has no inspection record)
lines8 itemsLine master (factory code held as FK)
parts8 itemsParts master (BRK-002 / ELC-002 / SUS-002 have no inspection record)
quality_specs11 itemsQuality standards table (some parts hold multiple standards = duplicate key)
inspections73 itemsInspection records (no F05 record + part_code fraud cases included)

JOIN Design Points for Demos:

  • factories No 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
  • inspections Detected in 3 cases with part_code = 'UNKNOWN-999' (invalid part code) → No.050
  • quality_specs part_code partially overlapped (before and after the revision of the standard) → No.047 confirmed
Show setup code and output (input 3)
[IN: 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}')
[OUT: 3]
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)
[IN: 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)')
[OUT: 4]
Data overview graph display completed (SVG 1/2)

Chart 1 for input 4


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

INNER JOIN(A, B, key)={ (a, b)∣a∈A,  b∈B,  a.key=b.key }\text{INNER JOIN}(A,\, B,\, \text{key}) = \{\,(a,\, b) \mid a \in A,\; b \in B,\; a.\text{key} = b.\text{key}\,\}

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

[IN: 5]
# 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
''')
[OUT: 5]
=== 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
shape: (1, 1)
inner_join_count
i64
73

Interpreting the results

  • factory_name and region have been added to inspection records, greatly improving readability
  • The total number of INNER JOIN is 73records (equal to the total number of inspections). You can verify that valid factory_id exist in all test records
  • Three cases of fraud part_code = 'UNKNOWN-999' were not ruled out because factory_id were 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

LEFT JOIN(A,B)⊇INNER JOIN(A,B)\text{LEFT JOIN}(A, B) \supseteq \text{INNER JOIN}(A, B)

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.

SituationINNER JOINLEFT 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

[IN: 6]
# 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
''')
[OUT: 6]
=== 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
shape: (5, 7)
factory_idfactory_nameregioncapacityinspection_counttotal_prodtotal_defect
strstrstri64i64i64i64
"F01""Tokyo Factory""Kanto"2000218046157
"F02""Osaka Factory""Kansai"1800216158140
"F03""Nagoya Factory""Central region"1600214395101
"F04""Fukuoka Factory""Kyushu"120010346678
"F05""Sendai Factory""Northeast"1000000

Interpreting the results

  • F05(Sendai Factory) is displayed as inspection_count = 0 and total_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

A RIGHT JOIN B≡B LEFT JOIN AA \text{ RIGHT JOIN } B \equiv B \text{ LEFT JOIN } A

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 writeHolding sideexcluded side
A LEFT JOIN BAll lines of AB-only row
A RIGHT JOIN BAll lines of BA line only
A FULL OUTER JOIN BAll rows from both sidesNone (supported since SQLite 3.39.0)

Run in Python

[IN: 7]
# 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}')
[OUT: 7]
=== 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 JOIN and FULL OUTER JOIN.
  • When emulating a full join on older SQLite versions, add only the unmatched rows from the other side with UNION ALL to 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.

Uptime=Actual production numbersFactory capacity×Number of days operated\text{Uptime} = \frac{\text{Actual production numbers}}{\text{Factory capacity} \times \text{Number of days operated}}

Run in Python

[IN: 8]
# 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
''')
[OUT: 8]
=== 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
shape: (4, 9)
factory_idfactory_nameregioncapacityn_recordstotal_prodtotal_defectdr_pctprod_per_capacity
strstrstri64i64i64i64f64f64
"F04""Fukuoka Factory""Kyushu"1200103466782.252.9
"F02""Osaka Factory""Kansai"18002057831282.213.2
"F03""Nagoya Factory""Central region"1600204247922.172.7
"F01""Tokyo Factory""Kanto"20002075961491.963.8

Interpreting the results

  • With region assigned, it becomes possible to compare Kanto vs Kansai vs Chubu vs Kyushu
  • prod_per_capacity divides 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

Loss amount per part=∑idefect_qtyi×unit_price\text{Loss amount per part} = \sum_{i} \text{defect\_qty}_i \times \text{unit\_price}

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

[IN: 9]
# 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
''')
[OUT: 9]
=== 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
shape: (5, 10)
part_codepart_namecategoryunit_pricen_recordstotal_prodtotal_defectdr_pctproduction_valuedefect_loss
strstrstri64i64i64i64f64i64i64
"ENG-002""Crankshaft""Engine parts"8500103466782.2529461000663000
"ELC-001""Alternator""electrical components"6800101992592.9613545600401200
"ENG-001""piston ring""Engine parts"12002083731591.910047600190800
"BRK-001""brake pad""brake parts"9502058391161.995547050110200
"SUS-001""shock absorber""suspension"2800101422352.46398160098000

Interpreting the results

  • defect_loss the 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

[IN: 10]
# 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
''')
[OUT: 10]
=== 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
shape: (7, 9)
factory_nameregionline_namepart_namecategoryn_recordstotal_prodtotal_defectdr_pct
strstrstrstrstri64i64i64f64
"Tokyo Factory""Kanto""Engine parts line""piston ring""Engine parts"104582901.96
"Tokyo Factory""Kanto""Brake Parts Line""brake pad""brake parts"103014591.96
"Osaka Factory""Kansai""Electrical Components Line""Alternator""electrical components"101992592.96
"Osaka Factory""Kansai""Engine parts line""piston ring""Engine parts"103791691.82
"Nagoya Factory""Central region""Suspension line""shock absorber""suspension"101422352.46
"Nagoya Factory""Central region""Brake Parts Line""brake pad""brake parts"102825572.02
"Fukuoka Factory""Kyushu""Engine parts line""Crankshaft""Engine parts"103466782.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 linesAfter INNER JOIN,Reasons for the increase
8 lines11 linesENG-001/002, BRK-001, ELC-001 each fan-out on two lines
NumberoflinesafterJOIN=∑k∈keys∣Ak∣×∣Bk∣Number of lines after \text{JOIN} = \sum_{k \in \text{keys}} | A_k| \times | B_k|

Here, ∣Ak∣|A_k| and ∣Bk∣|B_k| are the number of times key kk appears at each table.

Run in Python

[IN: 11]
# 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
''')
[OUT: 11]
=== 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
shape: (8, 3)
part_codepart_namespec_count
strstri64
"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) and quality_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_specs standards (line 1 → line 0).
  • To use the latest specification, find the maximum effective_from per 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:

  1. Number of cases before merging: SELECT COUNT(*) FROM parts → 8
  2. After INNER JOIN: SELECT COUNT(*) FROM parts INNER JOIN quality_specs ... → 11 cases (increase)
  3. After LEFT JOIN: SELECT COUNT(*) FROM parts LEFT JOIN quality_specs ... → 12 records (including the NULL line in SUS-002)
  4. Identifying duplicate keys: GROUP BY key HAVING COUNT(*) > 1

Run in Python

[IN: 12]
# 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
''')
[OUT: 12]
=== 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
shape: (4, 2)
part_codespec_count
stri64
"BRK-001"2
"ELC-001"2
"ENG-001"2
"ENG-002"2

Interpreting the results

  • INNER JOIN After that, the number of parts items increased from 8 to 11. quality_specs The cause is four components (ENG-001/002, BRK-001, ELC-001) that have duplicate keys
  • LEFT JOIN After 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(*) > 1 Identify 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

Uninspected part codes={p∈parts.part_code∣p∉inspections.part_code}.\text{Uninspected part codes} = \{p\in\text{parts.part\_code}\mid p\notin\text{inspections.part\_code}\}.
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

[IN: 13]
# 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
''')
[OUT: 13]
=== ① 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
shape: (3, 5)
part_codepart_namecategoryunit_pricesupplier_code
strstrstri64str
"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"
[IN: 14]
# 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)')
[OUT: 14]
Completion of Display of Inspection Count Graph by Part (SVG 2/2)

Chart 1 for input 14

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 NULL is an anti-join pattern. NOT EXISTS is another way to express the same test.
  • NOT IN behaves 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

Orphan records={i∈inspections∣i.part_code∉parts.part_code}.\text{Orphan records} = \{i\in\text{inspections}\mid i.\text{part\_code}\notin\text{parts.part\_code}\}.
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

[IN: 15]
# 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
''')
[OUT: 15]
=== 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
shape: (3, 4)
factory_idline_codeorphaned_countorphaned_code
strstri64str
"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_check is NULL. These are records with invalid codes that do not exist in the parts master
  • 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:
    1. orphaned_count Contact data managers at factories and lines with high levels of
    2. Identify the correct part_code and fix it with UPDATE or DELETE
    3. Adding foreign key constraints (FOREIGN KEY) to prevent recurrence
  • LEFT JOIN + WHERE IS NULL Pattern 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 IssuesSQL Patterns
Factory name and region added to the track recordINNER JOIN factories
Unit price × Calculate loss amount based on number of defectsINNER JOIN parts + SUM(defect * price)
Include factories with no inspectionsFROM factories f LEFT JOIN inspections i ON ... + COALESCE(...)
Cross-table KPIs of 3 or more tablesJOIN factories JOIN lines JOIN parts
Prevention of miscalculations due to overlapping quality standardsCheck COUNT(*) before and after JOIN
Identification of uninspected parts and unoperated linesLEFT JOIN ... WHERE IS NULL
Detecting and correcting invalid part codesLEFT 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.

exerciseMain SQLKey Points for Use in Manufacturing
No.041INNER JOINBasic Combination with Factory Name and Unit Price Added to Performance
No.042LEFT JOINIdentifying factories with zero inspection records based on a whole-factory standard
No.043RIGHT JOINUnderstanding the Equivalence with LEFT JOIN
No.044JOIN factoriesKPI (Defect Rate/Occupancy Rate) Aggregation by Factory
No.045JOIN partsLoss Ranking by Part
No.046JOIN × 3 chainCross-section analysis of factory + line + parts + inspection records
No.047Identifying duplicate keysIncrease in the number of rows due to duplicate quality standards tables
No.048Number of AssertionsQuality assurance through COUNT(*) before and after JOIN
No.049LEFT JOIN + WHERE IS NULLAutomatic identification of uninspected parts
No.050LEFT JOIN + WHERE IS NULLAutomatic 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.