SQLite UNION and UNION ALL: Define Duplicate Rows Before Combining Drone Inventory Records
Compare complete-row and identifier-only unions on two constructed inventory extracts, preserving repeated observations and missing-ID findings.

Define the identity question before combining extracts
Combining two drone inventory extracts can appear to be a simple append operation until repeated records disappear from a report. The SQL operator matters, but so do the selected columns. Two observations sharing an asset identifier may still describe different passes. If a query keeps both identifier and pass label, its idea of a duplicate differs from a query returning only identifiers. Before using a combined list to judge a handoff, state which records should remain distinguishable and what the result is intended to represent.
This tutorial uses invented asset and pass values in two small in-memory tables. It does not open a customer inventory, modify a GeoPackage, merge surveyed geometries, or describe a NiVO export schema. The first extract contains A/P1 twice and a missing identifier with P1. The second contains A/P2, B/P2, and another missing identifier with P1. The catalogue photograph provides separate product context. The example compares query outputs while preserving the original teaching inputs, without deciding whether any observation should actually be deleted.
Read UNION as duplicate removal over the returned row
SQLite documents UNION ALL as returning every row from both input SELECT statements. UNION removes duplicate result rows. Its compound-query duplicate comparison treats NULL as equal to another NULL, while the selected result columns define the row being compared. Consequently, retaining pass_label allows A/P1 and A/P2 to remain different rows. Selecting asset_id alone removes that distinction from the result. This is a query-scope decision rather than evidence that the physical asset or the underlying observation changed.
For these six supplied records, the two-column UNION ALL returns six rows. The two-column UNION returns four rows: the missing-ID/P1 row, A/P1, A/P2, and B/P2. An identifier-only UNION returns three rows containing NULL, A, and B. The last number must not be reported as three known assets, because one returned identifier is missing. These results answer different questions. Keep their column lists and operator names visible rather than choosing whichever output total seems most convenient for the expected delivery count.

Product context only; this photograph does not depict the constructed examples in this article.
Run three fixed queries on the same isolated records
Run the following Python function locally. It accepts two small lists or tuples of two-field records. The identifier may be text or None, while the pass label must be text. Both columns use explicit text affinity and BINARY collation. Values are inserted through parameters into a fresh in-memory database, and the connection closes after the comparison. Each query has a final ORDER BY so the demonstration has reproducible output ordering. The sixty-four-record input limit is a teaching safeguard, not an SQLite capacity restriction.
The returned dictionary retains the complete ordered rows instead of returning only totals. That lets another reviewer see exactly which distinctions were preserved or removed. The function applies no identifier normalization, latest-pass selection, geometry operation, or record repair. Input validation defines this small example profile; it does not validate a real inventory schema. Run it with the supplied examples before adapting a query to an actual receiving workflow, and keep any proposed business rule separate from the behavior demonstrated by the three fixed statements.
import sqlite3
def compare_unions(first, second):
for rows in (first, second):
if type(rows) not in (list, tuple) or len(rows) > 64:
raise ValueError("Teaching profile: at most 64 records per extract")
for row in rows:
if type(row) not in (list, tuple) or len(row) != 2:
raise ValueError("Expected asset_id and pass_label")
if row[0] is not None and type(row[0]) is not str:
raise ValueError("Expected text asset_id or None")
if type(row[1]) is not str:
raise ValueError("Expected text pass_label")
con = sqlite3.connect(":memory:")
try:
for table in ("first_extract", "second_extract"):
con.execute("CREATE TABLE " + table +
"(asset_id TEXT COLLATE BINARY, pass_label TEXT COLLATE BINARY)")
con.executemany("INSERT INTO first_extract VALUES(?, ?)", first)
con.executemany("INSERT INTO second_extract VALUES(?, ?)", second)
pair = "SELECT asset_id, pass_label FROM first_extract {} "
pair += "SELECT asset_id, pass_label FROM second_extract ORDER BY 1, 2"
ids = "SELECT asset_id FROM first_extract UNION "
ids += "SELECT asset_id FROM second_extract ORDER BY 1"
return {"all_pairs": con.execute(pair.format("UNION ALL")).fetchall(),
"unique_pairs": con.execute(pair.format("UNION")).fetchall(),
"unique_ids": con.execute(ids).fetchall()}
finally:
con.close()
# Constructed extracts, not actual inspection records.
a = [("A", "P1"), ("A", "P1"), (None, "P1")]
b = [("A", "P2"), ("B", "P2"), (None, "P1")]
print(compare_unions(a, b))Test missing identifiers without inventing an asset identity
The repeated NULL/P1 rows collapse into one row in the two-column UNION. That is the duplicate-comparison behavior of this query, not a finding that both missing identifiers refer to the same real asset. Preserve the source records when investigating the unknown identities. If separate observations require their own identity, retain the appropriate original record key and source information in the real workflow. Do not manufacture a shared asset identifier merely to explain why a duplicate-removing query returned one row.
Try two missing identifiers with different pass labels. The pair result should retain both rows, while the identifier-only result still contains one NULL. Also test an empty extract and repeated records confined to one side. UNION can remove duplicates originating within one input as well as duplicates shared across the inputs. These small cases explain why a union result cannot, on its own, report which source created an observation or whether a missing value was repaired. Keep unresolved data-quality findings alongside the combined result.
Preserve provenance and comparison rules when expanding the query
Adding a source label to every selected row can intentionally preserve provenance, but it also changes which complete rows compare as duplicates. Two otherwise identical records carrying different source labels remain distinct under a UNION over all those columns. Decide whether the output should represent observations, source-specific records, or a separate asset register before changing the projection. The function here uses pass labels already supplied as data; it does not invent source provenance or infer an origin from the order of returned rows.
Test letter case, leading zeros, blank identifiers, and whitespace under the explicit text and BINARY profile. A and a, or 007 and 7, remain distinct teaching values. An empty string is text, while None represents SQL NULL. A real schema may use different comparison or validation rules, so retain those definitions before comparing outputs across applications. Parameter binding keeps record values separate from SQL syntax. The table names and operators assembled inside this function are fixed local choices rather than user-supplied query fragments.
The final sort makes the example easy to compare, but it does not preserve original observation order or provide a missing source record key. Repeated identical pairs in the ALL result cannot be traced back individually from these two selected fields alone. If that trace matters, preserve the original record identity in a separate diagnostic or an appropriately defined output. Treat provenance as information that must be retained deliberately, rather than something recoverable from a compact result after its distinguishing columns were omitted.
Deliver the combined row definition with the result
For a real inventory handoff, retain both input identities, selected columns, exact compound query, comparison policy, query version, and an independently checked small example. State whether repeated records were retained, collapsed in a result, or separately reviewed for an authorized cleanup. Keep the original observations available. If a receiver expects one row per physical asset, document the additional identity and relationship rules needed to produce that register rather than assuming that UNION implements those rules automatically.
In a NiVO-related review, this method explains why the same six supplied records can yield six appended rows, four distinct pairs, or three identifier rows including one missing value. It does not establish completed inspections, physical asset uniqueness, mapped coverage, or delivery acceptance. Preserve the unchanged extracts and continue the independent checks required by the project. The useful outcome is a reproducible combination policy with the selected row meaning attached, so a smaller report is not mistaken for proof that observations were safely removed or assets were reconciled.



