Query assay tables with SQL and DuckDB
A sample table can fit on one screen while its assay table contains millions of rows. Loading every measurement into a data frame is unnecessary when the question concerns three features. DuckDB lets SQL select the required rows and columns from a Parquet file, join them to sample metadata, and return a small result to Python.
This example uses invented measurements for paired control and treated samples. Its feature names and values have no biological interpretation. The lesson teaches file queries and valid joins; the displayed changes are descriptive summaries, not results from a biological experiment.
Download the Parquet measurements,
sample metadata, and
selected rows.
Place them in an inputs folder. The selected CSV contains the same three
features as the final query and allows a separate calculation without SQL.
The example uses Python with DuckDB 1.4.2.
Read files without importing the complete table
Section titled “Read files without importing the complete table”CREATE VIEW assigns a query a name. It does not copy the Parquet measurements
into a database table. Here the database exists only inside the Python process;
the input files remain the durable source.
import csvimport jsonfrom collections import defaultdictfrom pathlib import Path
import duckdbimport matplotlib.pyplot as pltimport numpy as np
output = Path("outputs")output.mkdir(exist_ok=True)connection = duckdb.connect()connection.execute("SET threads = 2")connection.execute("SET memory_limit = '1GB'")connection.execute(""" CREATE VIEW assay AS SELECT * FROM read_parquet('inputs/sql_assay.parquet')""")connection.execute(""" CREATE VIEW samples AS SELECT * FROM read_csv('inputs/sql_samples.csv', all_varchar = true)""")counts = connection.execute(""" SELECT COUNT(*) AS rows, COUNT(DISTINCT sample_id) AS samples, COUNT(DISTINCT feature_id) AS features FROM assay""").fetchone()print(f"Measurement rows: {counts[0]:,}")print(f"Samples: {counts[1]}")print(f"Features: {counts[2]:,}")Measurement rows: 1,200,000Samples: 240Features: 5,000SELECT names the requested columns or calculations. FROM names their source.
COUNT(*) counts rows, whereas COUNT(value) would count only nonmissing
values. The next checks require measurements to be present, so these two counts
cannot silently describe different sample sets.
Establish the keys before a join
Section titled “Establish the keys before a join”Each measurement has one sample and one feature. Each sample must have exactly one metadata record. A duplicated sample key multiplies measurements during a join, even when every value is correct.
duplicate_samples = connection.execute(""" SELECT sample_id FROM samples GROUP BY sample_id HAVING COUNT(*) != 1""").fetchall()duplicate_measurements = connection.execute(""" SELECT sample_id, feature_id FROM assay GROUP BY sample_id, feature_id HAVING COUNT(*) != 1""").fetchall()unmatched_samples = connection.execute(""" SELECT DISTINCT sample_id FROM assay ANTI JOIN samples USING (sample_id)""").fetchall()invalid_values = connection.execute(""" SELECT COUNT(*) FROM assay WHERE sample_id IS NULL OR feature_id IS NULL OR value IS NULL""").fetchone()[0]invalid_metadata = connection.execute(""" SELECT COUNT(*) FROM samples WHERE sample_id IS NULL OR donor IS NULL OR condition IS NULL OR condition NOT IN ('control', 'treated')""").fetchone()[0]invalid_pairs = connection.execute(""" SELECT donor FROM samples GROUP BY donor HAVING COUNT(*) != 2 OR COUNT(DISTINCT condition) != 2""").fetchall()assert not duplicate_samples and not duplicate_measurementsassert not unmatched_samples and invalid_values == 0assert invalid_metadata == 0 and not invalid_pairsprint("Duplicate sample keys:", len(duplicate_samples))print("Duplicate measurement keys:", len(duplicate_measurements))print("Unmatched samples:", len(unmatched_samples))print("Invalid donor pairs:", len(invalid_pairs))Duplicate sample keys: 0Duplicate measurement keys: 0Unmatched samples: 0Invalid donor pairs: 0An ANTI JOIN returns keys that have no match. An ordinary inner join would
discard those rows, which can hide absent sample metadata. Fix a missing or
duplicated record at its source before you calculate a group summary.
See what one duplicated record changes
Section titled “See what one duplicated record changes”The temporary bad_samples view adds a second metadata record for S001.
The resulting row count demonstrates the error. The analysis continues with
the original validated samples view.
connection.execute(""" CREATE VIEW bad_samples AS SELECT * FROM samples UNION ALL SELECT * FROM samples WHERE sample_id = 'S001'""")valid_rows = connection.execute(""" SELECT COUNT(*) FROM assay JOIN samples USING (sample_id)""").fetchone()[0]invalid_rows = connection.execute(""" SELECT COUNT(*) FROM assay JOIN bad_samples USING (sample_id)""").fetchone()[0]assert valid_rows == counts[0]print(f"Rows after the valid join: {valid_rows:,}")print(f"Rows after the duplicated join: {invalid_rows:,}")print(f"Extra measurements: {invalid_rows - valid_rows:,}")Rows after the valid join: 1,200,000Rows after the duplicated join: 1,205,000Extra measurements: 5,000DISTINCT is not a general repair for this error. Two metadata records can
disagree about treatment or donor while sharing a sample identifier. Removing
one record without resolving that disagreement chooses an analysis design by
accident.
Select features and preserve donor pairs
Section titled “Select features and preserve donor pairs”The WHERE clause restricts the calculation to three named features. The
parameter placeholders keep feature values separate from SQL syntax. The
common table expression named selected gives the filtered join a local name
inside this query.
features = ["G00001", "G00002", "G00003"]paired_query = """ WITH selected AS ( SELECT a.feature_id, s.donor, s.condition, a.value FROM assay AS a JOIN samples AS s USING (sample_id) WHERE a.feature_id IN (?, ?, ?) ) SELECT feature_id, donor, MAX(CASE WHEN condition = 'control' THEN value END) AS control, MAX(CASE WHEN condition = 'treated' THEN value END) AS treated, treated - control AS change FROM selected GROUP BY feature_id, donor HAVING COUNT(*) = 2 AND COUNT(DISTINCT condition) = 2 ORDER BY feature_id, donor"""paired = connection.execute(paired_query, features).fetchdf()assert len(paired) == len(features) * 120summary = paired.groupby("feature_id", sort=True).agg( donors=("donor", "size"), mean_change=("change", "mean")).reset_index()paired.to_csv(output / "paired_changes.csv", index=False)summary.to_csv(output / "feature_summary.csv", index=False)print(summary.to_string(index=False, float_format="%.3f"))feature_id donors mean_change G00001 120 11.975 G00002 120 -8.025 G00003 120 0.050CASE places the two conditions into separate columns. MAX then selects the
single value in each column. The earlier key checks make that operation valid;
without them, MAX could conceal duplicated observations. The HAVING clause
requires both conditions for every returned feature and donor.
One donor contributes one difference for each feature. The million-row assay table does not create a million independent replicates. In another dataset, report excluded feature and donor pairs before interpreting an average change.
Check the result without the SQL calculation
Section titled “Check the result without the SQL calculation”The selected CSV makes the arithmetic inspectable. A dictionary groups its values by feature and donor, and the subtraction below must agree with every SQL result row. This comparison detects a reversed contrast, a wrong join key, or an incorrect aggregation.
with open("inputs/sql_samples.csv", newline="") as handle: metadata = {row["sample_id"]: row for row in csv.DictReader(handle)}values = defaultdict(dict)with open("inputs/sql_selected_truth.csv", newline="") as handle: for row in csv.DictReader(handle): sample = metadata[row["sample_id"]] key = (row["feature_id"], sample["donor"]) values[key][sample["condition"]] = int(row["value"])expected = {}for key, pair in values.items(): assert set(pair) == {"control", "treated"} expected[key] = pair["treated"] - pair["control"]for row in paired.itertuples(index=False): key = (row.feature_id, row.donor) assert row.control == values[key]["control"] assert row.treated == values[key]["treated"] assert row.change == expected[key]assert len(expected) == len(paired)for row in summary.itertuples(index=False): differences = [] for key, value in expected.items(): if key[0] == row.feature_id: differences.append(value) assert np.isclose(row.mean_change, sum(differences) / len(differences))(output / "verification.json").write_text( json.dumps({"verified_pairs": len(expected), "join_rows": valid_rows}, indent=2) + "\n")print("Independently verified donor differences:", len(expected))Independently verified donor differences: 360Inspect the query and display the summary
Section titled “Inspect the query and display the summary”EXPLAIN reports the operations DuckDB plans to perform. The saved plan shows
the Parquet scan, feature filter, join, and aggregation. Selecting only needed
columns permits projection pushdown; suitable Parquet statistics can also
exclude row groups that cannot match the filter. The file layout affects that
benefit, so a small returned table does not by itself prove a small disk read.
plan = connection.execute("EXPLAIN " + paired_query, features).fetchone()[1](output / "query_plan.txt").write_text(plan + "\n")figure, axes = plt.subplots(figsize=(7.2, 4.5))axes.barh(summary.feature_id, summary.mean_change, color="#32658b")axes.axvline(0, color="#333333", linewidth=0.8)axes.set_xlabel("Mean treated minus control, arbitrary units")axes.set_ylabel("Invented feature")axes.set_title("Each difference preserves the donor pair")axes.spines[["top", "right"]].set_visible(False)figure.tight_layout()figure.savefig(output / "sql_duckdb_changes.png", dpi=160)plt.close(figure)connection.close()
The result can feed a report or a separate statistical analysis. SQL controls which measurements reach that analysis; it does not choose the experimental unit, normalization, or statistical model for you.
Scientific references
Section titled “Scientific references”Raasveldt and Mühleisen, 2019 describe DuckDB as an analytical database that runs inside another process.
Further reading
Section titled “Further reading”The DuckDB 1.4 Parquet guide explains column projection, filters, and the file statistics used to skip data. Read it before attributing a performance improvement to the number of returned rows.
The join documentation explains inner, outer, semi, and anti joins. These operations answer different questions about unmatched sample identifiers.
The Python database API documents connections, parameter placeholders, and result conversion. It provides the syntax needed to turn this example into a function for another table.