AI Wiki中文/EN

SQL for AI data work: one row, one prediction

AI 数据工作的 SQL

Build point-in-time features in SQLite while checking join multiplicity, late arrivals, missing history and labels.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Two readings should not become six

A workshop wants to predict whether a press will need attention. At prediction time 10, the database contains two eligible sensor readings and three maintenance tickets. Join all three tables and count the sensor IDs: the answer is six. The query runs successfully. The feature is wrong.

SQL describes a requested result over tables. For AI work, the first question is what one output row represents. Here it is one prediction occasion, identified by prediction_id, rather than one machine or one sensor event. The same press can have predictions at times 10 and 20 with different information available.

We will build that table in an actual in-memory SQLite database, preserve predictions with no history, and keep future labels separate. The naive join supplies a useful baseline: its wrong counts are small enough to inspect by hand.

Keys, multiplicity and time determine the feature

Establish the output unit

predictions stores a unique prediction ID, an entity and a prediction time. sensors and tickets each have their own unique event ID. An entity may occur many times in all three tables. Joining on entity alone therefore does not establish a one-to-one relationship.

For a prediction p, let a and b be the numbers of eligible sensor and ticket rows. An inner join of both histories contains every matching pair:

Njoined(p)=apbp.N_{\mathrm{joined}}(p)=a_p b_p.

Our fixture has a=2 and b=3. Each sensor appears three times; each ticket appears twice. The correct fix is to aggregate each history at prediction-ID level, then join those summaries. DISTINCT is not a general repair: two different sensor events may legitimately have the same measured value.

SQLite describes joins through their Cartesian combinations and filters. Its logical description does not require the engine to materialize the entire Cartesian product. Output order also needs an explicit ORDER BY; our unique prediction ID breaks ties. SELECT semantics

Use the information that existed at the decision

Every timestamp in this example is an integer minute on one shared clock. A sensor record has both an occurrence time and the time it became available to the prediction system. For prediction p on entity e, the eligible set is:

Sp={r:r.entity=ep, r.occurred_at<tp, r.available_at<tp}.S_p=\{r:r.\mathrm{entity}=e_p,\ r.\mathrm{occurred\_at}<t_p,\ r.\mathrm{available\_at}<t_p\}.

Strict inequalities exclude records at the prediction boundary. A reading taken at time 4 but delivered at time 15 cannot inform a prediction made at 10. It may inform one made at 20. Keeping only the occurrence condition would rewrite what the earlier system knew. This is a data-contract choice, not a property SQL can infer.

The program allows either order of the two timestamps and checks both. If a real source guarantees that delivery follows occurrence, validate that extra invariant upstream. Corrections to historical values also need versioned records: a trustworthy availability timestamp cannot rescue an overwritten value.

Preserve absence without inventing a measurement

The left join inside each summary preserves a prediction even when no history matches. Count the non-null event ID, not COUNT(*), which would count the placeholder row. In SQLite, COUNT(column) skips nulls; SUM and AVG return null when there are no non-null inputs. We retain that distinction. Aggregate functions

fp={(∣Sp∣, ∑r∈Spr.value, ∣Sp∣−1∑r∈Spr.value)∣Sp∣>0,(0, NULL, NULL)∣Sp∣=0.f_p=\begin{cases}(|S_p|,\ \sum_{r\in S_p}r.\mathrm{value},\ |S_p|^{-1}\sum_{r\in S_p}r.\mathrm{value})&|S_p|>0,\\(0,\ \mathrm{NULL},\ \mathrm{NULL})&|S_p|=0.\end{cases}

No reading is different from a reading of zero. Python receives SQL NULL as None. An imputation rule, if needed, belongs to a later fitted preprocessing step.

The time filters belong in the left join’s ON clause. Moving them into WHERE rejects the null-extended rows and loses predictions without history. Outer joins and filtering

Build and inspect a point-in-time table

This complete Python 3.12 program uses only the standard library. Each input table is a list or tuple of at most 1,000 rows; IDs and entity names are nonempty strings of at most 40 characters. Times are integers from 0 to 1,000,000, readings are integers from −1,000 to 1,000, and labels are exactly integer 0 or 1. Booleans and wrong row widths are rejected. Empty tables are valid. A history for an entity with no prediction is allowed and contributes nothing.

Primary keys reject duplicate IDs. Targets reference prediction IDs and must have a known time strictly after their prediction; labels may be absent. This simplified contract does not define a clinical or industrial outcome window. Features never read the target table.

All inserts form one transaction after schema creation. with con commits or rolls back that transaction; closing separately releases the connection. Foreign-key enforcement is enabled and checked before insertion. Bound ? parameters carry values, including the optional entity filter, while the SQL structure stays fixed. Python sqlite3 · SQLite foreign keys

import sqlite3
from contextlib import closing


FEATURE_SQL = '''
WITH cohort AS (
  SELECT prediction_id, entity, prediction_at FROM predictions
  WHERE (? IS NULL OR entity = ?)
), sensor_summary AS (
  SELECT p.prediction_id, COUNT(s.sensor_id) AS n,
         SUM(s.value) AS total, AVG(s.value) AS mean
  FROM cohort AS p LEFT JOIN sensors AS s
    ON s.entity = p.entity AND s.occurred_at < p.prediction_at
       AND s.available_at < p.prediction_at
  GROUP BY p.prediction_id
), ticket_summary AS (
  SELECT p.prediction_id, COUNT(t.ticket_id) AS n
  FROM cohort AS p LEFT JOIN tickets AS t
    ON t.entity = p.entity AND t.occurred_at < p.prediction_at
       AND t.available_at < p.prediction_at
  GROUP BY p.prediction_id
)
SELECT p.prediction_id, p.entity, p.prediction_at,
       s.n, s.total, s.mean, t.n
FROM cohort AS p
JOIN sensor_summary AS s ON s.prediction_id = p.prediction_id
JOIN ticket_summary AS t ON t.prediction_id = p.prediction_id
ORDER BY p.prediction_id
'''


def text(value):
    if type(value) is not str or not 1 <= len(value) <= 40:
        raise ValueError('IDs must be nonempty strings of at most 40 characters')
    return value


def integer(value, low=0, high=1000000):
    if type(value) is not int or not low <= value <= high:
        raise ValueError('integer outside the declared range')
    return value


def records(rows, validators):
    if type(rows) not in (tuple, list) or len(rows) > 1000:
        raise ValueError('each table needs a list/tuple of at most 1000 rows')
    out = []
    for row in rows:
        if type(row) not in (tuple, list) or len(row) != len(validators):
            raise ValueError('row width differs from schema')
        out.append(tuple(check(value) for check, value in zip(validators, row)))
    return out


def database(predictions, sensors, tickets, targets=()):
    p = records(predictions, (text, text, integer))
    s = records(sensors, (text, text, integer, integer,
                         lambda v: integer(v, -1000, 1000)))
    t = records(tickets, (text, text, integer, integer))
    y = records(targets, (text, lambda v: integer(v, 0, 1), integer))
    times = {pid: at for pid, entity, at in p}
    if any(pid in times and known <= times[pid] for pid, label, known in y):
        raise ValueError('this example requires labels known after prediction')
    con = sqlite3.connect(':memory:', isolation_level='DEFERRED',
                          autocommit=sqlite3.LEGACY_TRANSACTION_CONTROL)
    try:
        con.execute('PRAGMA foreign_keys = ON')
        if con.execute('PRAGMA foreign_keys').fetchone() != (1,):
            raise RuntimeError('foreign-key enforcement unavailable')
        con.executescript('''
          CREATE TABLE predictions(
            prediction_id TEXT PRIMARY KEY NOT NULL,
            entity TEXT NOT NULL, prediction_at INTEGER NOT NULL);
          CREATE TABLE sensors(
            sensor_id TEXT PRIMARY KEY NOT NULL, entity TEXT NOT NULL,
            occurred_at INTEGER NOT NULL, available_at INTEGER NOT NULL,
            value INTEGER NOT NULL);
          CREATE TABLE tickets(
            ticket_id TEXT PRIMARY KEY NOT NULL, entity TEXT NOT NULL,
            occurred_at INTEGER NOT NULL, available_at INTEGER NOT NULL);
          CREATE TABLE targets(
            prediction_id TEXT PRIMARY KEY NOT NULL REFERENCES predictions,
            label INTEGER NOT NULL CHECK(label IN (0,1)),
            known_at INTEGER NOT NULL);
        ''')
        with con:
            con.executemany('INSERT INTO predictions VALUES(?,?,?)', p)
            con.executemany('INSERT INTO sensors VALUES(?,?,?,?,?)', s)
            con.executemany('INSERT INTO tickets VALUES(?,?,?,?)', t)
            con.executemany('INSERT INTO targets VALUES(?,?,?)', y)
        return con
    except BaseException:
        con.close()
        raise


def features(con, entity=None):
    # con must be the unmodified database returned above.
    if entity is not None:
        text(entity)
    return con.execute(FEATURE_SQL, (entity, entity)).fetchall()


def fixture():
    predictions = [('p1', 'press', 10), ('p2', 'press', 20),
                   ('p3', 'lamp', 10), ('p4', 'press', 0)]
    sensors = [('s1', 'press', 2, 3, 4), ('s2', 'press', 5, 5, 8),
               ('s3', 'press', 4, 15, 100), ('s4', 'press', 10, 10, 12)]
    tickets = [('t1', 'press', 1, 1), ('t2', 'press', 6, 7),
               ('t3', 'press', 8, 9)]
    targets = [('p1', 1, 12), ('p2', 0, 22), ('p3', 0, 12)]
    return predictions, sensors, tickets, targets


def main():
    with closing(database(*fixture())) as con:
        for row in features(con):
            print(row)
        naive = con.execute('''
          SELECT COUNT(s.sensor_id), SUM(s.value), COUNT(t.ticket_id)
          FROM predictions AS p JOIN sensors AS s
            ON s.entity=p.entity AND s.occurred_at<p.prediction_at
               AND s.available_at<p.prediction_at
          JOIN tickets AS t
            ON t.entity=p.entity AND t.occurred_at<p.prediction_at
               AND t.available_at<p.prediction_at
          WHERE p.prediction_id=?
        ''', ('p1',)).fetchone()
        print('raw join:', naive)
        print('labels:', con.execute('''SELECT prediction_id, label
              FROM targets ORDER BY prediction_id''').fetchall())


if __name__ == '__main__':
    main()

Output:

('p1', 'press', 10, 2, 12, 6.0, 3)
('p2', 'press', 20, 4, 124, 31.0, 3)
('p3', 'lamp', 10, 0, None, None, 0)
('p4', 'press', 0, 0, None, None, 0)
raw join: (6, 36, 6)
labels: [('p1', 1), ('p2', 0), ('p3', 0)]

The tuple fields are prediction ID, entity, prediction time, sensor count, sensor sum, sensor mean and ticket count. At time 10 the eligible readings are 4 and 8: count 2, sum 12, mean 6. At time 20 the delayed 100 and boundary reading 12 have become eligible: count 4, sum 124, mean 31. The lamp and time-zero prediction survive with no history. The deliberately raw join reports (6,36,6) for the first prediction.

Each left-joined summary has exactly one group per selected prediction, including unmatched ones. Their final joins are therefore one-to-one on the unique prediction ID. This establishes the promised output cardinality. Selecting one entity does not alter another prediction’s history, and sorting the returned rows does not make their IDs into features.

With P predictions, S sensor rows and T ticket rows, the two history joins have at most P*max(1,S) and P*max(1,T) logical rows before grouping, rather than joining both histories into as many as P*S*T rows. This is a cardinality bound, not a guaranteed running time or peak-memory measurement: SQLite may choose indexes, scans and temporary grouping structures. The Python result occupies O(P) rows; the in-memory database stores the input and its indexes. For larger tables, inspect the actual query plan and appropriate entity/time indexes. An index does not correct a wrong join.

A valid table can still describe the wrong experiment

The database constraints protect declared structure. Python validation supplies the stronger numeric and label-timing rules; arbitrary later SQL writes can bypass those rules, so features expects the unmodified database returned by database. The foreign key ensures a target has an existing prediction, not that the label was measured correctly. Its primary key ensures at most one target, not that every prediction has one.

The supplied bounds keep integer feature sums exact and small; averages are floating-point values. Larger values, nullable raw readings, different SQL engines or timestamp types require a revised contract. NULL may have several business meanings, so a count column is useful context rather than a full missingness model.

No model is trained here. Export labels by prediction ID, define a training and evaluation split, and fit any preprocessing only within training. Repeated predictions for one machine may share history; a random row split can answer a different question from evaluation on future times or unseen machines. A clean query alone does not establish generalization.

Parameter binding protects value boundaries; it is not a mechanism for accepting arbitrary table names or SQL fragments. This program uses fixed schema names and creates no files, network connections or external database changes.

Audit the row before fitting the model

  1. Count the fanout. Two sensors and three tickets match one prediction. What does the raw inner join count, and would SUM(DISTINCT value) always repair its sensor sum?
Trace an event through the join

Answer: It contains six rows, so both event-ID counts are six. Each sensor value is repeated three times. SUM(DISTINCT value) would wrongly merge two legitimate readings with equal values; aggregate the sensor history independently by prediction ID instead.

  1. Place a delayed reading. A reading occurs at 4, becomes available at 15, and predictions happen at 10, 15 and 20. Which predictions can use it?
Apply both strict inequalities

Answer: Only time 20. It is unavailable at 10 and exactly on the excluded availability boundary at 15. Occurrence time alone would incorrectly include it in both earlier predictions.

  1. Keep an empty history. What should the sensor count and mean be for the lamp? What happens if the right-hand time conditions move from ON into WHERE?
Follow the null-extended row

Answer: Count zero and mean NULL, represented as None in Python. The lamp remains a prediction. With the time conditions in WHERE, comparisons involving the unmatched null values are not true, so that row is removed; COUNT(*) inside the original left-join group would instead misleadingly count one row.

  1. Separate labels from features. Why does the target primary key plus foreign key not guarantee a complete training dataset?
Distinguish uniqueness from coverage

Answer: They prevent duplicate target IDs and targets for nonexistent predictions. They do not require a target for every prediction; p4 has none. Check label coverage explicitly and choose how to handle unlabeled predictions. Joining only labeled rows changes the selected population, and future labels must remain outside the feature query.

Follow the query from meaning to execution

The SQLite SELECT specification explains multiplicity and filtering; its aggregate reference explains how absence affects counts and averages. Together they provide a precise way to review a feature table before discussing query speed. Foreign-key documentation adds structural integrity, while the Python interface makes parameter binding and transaction boundaries explicit.

Continue with data leakage for experimental consequences and dataframes for labeled in-memory operations. The transferable habit is to preserve one declared row unit and one declared information boundary through every transformation.

Make a prediction, then check

A reading occurred at time 4 and arrived at 15. Can a prediction at time 10 use it?

Choose one answer

Learning objectives

  • Define the prediction row unit and prevent multiplicative history joins.
  • Apply both occurrence and availability cutoffs while preserving absent histories.
  • Separate feature semantics, structural constraints, parameters and transaction boundaries.

Prerequisites & connections

Explore related knowledge →

References

  1. SELECT — SQLite
    SQLite developers
  2. Built-in Aggregate Functions — SQLite
    SQLite developers
  3. sqlite3 — Python 3.12 documentation
    Python Software Foundation
  4. SQLite Foreign Key Support
    SQLite developers

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-06 · Codex technical check: primary-source locations, original runnable models, independent mathematical and computational references, bilingual review and second-agent cross-checks; not independent human peer review.

  • Eight tests pass under CPython 3.12.4 with actual standard-library SQLite 3.45.3. An independent event-release sweep sorts predictions before same-time releases, activates records at max(occurred_at,available_at), and accumulates per-entity state. Six fixtures and their reversed insertion orders agree with all returned feature fields, including empty cohorts, empty histories, future occurrence and late arrival. This does not reproduce per-prediction relational grouping.
  • Targeted tests execute the ON/WHERE and COUNT(*) absence counterexample, repeated equal-valued events versus SUM(DISTINCT), strict cutoff behavior, SQL-looking entity parameter binding, numeric/type/row-width constraints and lower/upper bounds. An SQLite authorizer forbids target reads during the feature query; labels and later sensor values can change without affecting the first prediction. A successful sensor insert followed by a duplicate-target error is actually rolled back, and orphan targets and duplicate prediction IDs are rejected.
  • Original complete EN/ZH articles contain identical full Python and six executed stdout lines, three matching displays, six anchors and four answered exercises. Strict MDX/KaTeX plus actual React HTML pass; prose and formulas were reread for Humanizer style, row-unit reasoning, label coverage and operational boundaries. No third-party examples or code are copied.
  • Status remains written with AI author checks only. This program builds a bounded feature table, not a trained predictor or a full point-in-time storage system. Raw source records are non-null, historical values are immutable by contract, and features expects the unmodified returned database. The stated P,S,T expressions bound logical row counts rather than database runtime or memory. No external database, production timing, whole-site acceptance or human review is claimed.
  • Root read both complete articles and full program; checked three formulas, four exercise answers and six common section anchors. Re-ran eight author tests on CPython 3.12.4 / SQLite 3.45.3 and strict MDX/KaTeX/React HTML. No revisions required; five frozen hashes match.
  • Independent scalar correlated subqueries, without any join or GROUP BY, match every output field of the CTE query for 12 prediction occasions, 60 sensor records and 40 tickets under four cohort filters. This checks the relational construction through a different SQL shape; the author separately supplies a non-SQL event-release reference.
  • Reviewed strict occurrence/availability boundaries, immutable-history scope, fanout, NULL versus zero, label coverage versus uniqueness, transaction rollback and in-memory-only execution. Structural constraints do not establish model generalization or a complete point-in-time data store.
  • Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
  • Publication navigation points published topics to complete articles and removes corresponding pending wording, retaining directory entries for unwritten targets. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.

Source locations checked:

  • SELECT — SQLite · Actually read official SELECT page lines 182 and 264–283 for logical processing versus actual execution and Cartesian join semantics; 288–313 for left-join null extension, ON versus WHERE and grouping; 423–427 for result order and tie ambiguity; 465–467 for WITH. The original prediction-grain/cardinality argument is scoped to these declared unique keys. No query-plan speedup is asserted or benchmarked.
  • Built-in Aggregate Functions — SQLite · Actually read aggregate reference lines 65–68 for DISTINCT and aggregate input ordering, 88–93 for AVG and COUNT, and 132–138 for SUM/total null behavior, integer results and overflow. Footer line 150 is dated 2025-11-13. Newer percentile/median functions on this live page are not used or claimed available in SQLite 3.45.3.
  • sqlite3 — Python 3.12 documentation · Actually read fixed /3.12 sqlite3 reference rendered 3.12.13: lines 132–136 for in-memory connections and isolation level; 898–928 for execute/executemany; 1225–1253 for qmark binding; 1411–1434 for commit/rollback and separate closure; 1564–1571 for explicit LEGACY_TRANSACTION_CONTROL and implicit DML begin. Actual program specifies the mode, enables foreign keys before any transaction and creates schema before the insertion transaction.
  • SQLite Foreign Key Support · Actually read official foreignkeys page lines 136–148 for parent/child key semantics and nullable references, and 149–167 for compile support, per-connection PRAGMA enabling/checking and inability to toggle inside a transaction. The program uses a non-null primary-key target reference and checks enforcement. Event entity strings need not appear in the cohort; no nonexistent entity foreign-key guarantee is asserted.
  • SELECT — SQLite · Root independently read SELECT logical processing and Cartesian join semantics lines 264–281 and outer-join/WHERE discussion around lines 288–299. Reviewed unique prediction-grain groups and cardinality separately from execution time.
  • Built-in Aggregate Functions — SQLite · Root independently read official COUNT and AVG definitions lines 88–93. Actual SQLite tests also execute integer SUM and empty-history null behavior; no newer aggregate functions are used.
  • sqlite3 — Python 3.12 documentation · Root independently read /3.12 connection context manager lines 1411–1434: commit or rollback, no automatic connection closure, and explicit closing. Inspected fixed qmark-bound statements and explicit legacy mode in the full program.
  • SQLite Foreign Key Support · Root independently read runtime enabling/checking and transaction restriction lines 149–167. Inspected non-null unique target key and enabled foreign-key enforcement before inserts.

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.