Second-Draft Verification Note (2026-10-15): This article has been revised against official documentation and sample code. Legacy logs are retained as "first-draft retained output" and do not serve as rerun evidence for this batch; see the link at the end for this batch's execution results. Software versions and server configurations depend on the actual deployment environment. StarRiver Notes, users, and orders are all fictional.
Annotation legend: [Documented] includes links to official documentation or original papers; [Industry Consensus] reflects standard engineering practice without a single canonical source; [Unverified / Conjecture] indicates unverified claims or author inference that should not be treated as settled fact.
One-Sentence Definition
SQL declaratively specifies the target of queries and data manipulations while the database engine selects an execution plan based on relational semantics and optimizer rules; exact syntax, constraints, and transactional behaviors vary across SQL dialects.
Why It Matters
- Nearly all core business records ultimately live in relational databases or data warehouses; ETL pipelines, product analytics, and AI evaluation reports all rely on SQL.
- Because SQL is declarative, the exact same query can be executed via different physical plans by the query optimizer depending on data volume and indexes (see k5.data.db-index), which requires a different mental model from imperative loops (see k1.prog.declarative).
- The most dangerous SQL bugs in production are not syntax errors—they are queries that run without error but silently return wrong numbers (three-valued
NULLlogic) and security vulnerabilities (SQL injection from string concatenation). Below we demonstrate both in a live database.
Principles & Diagram
Logical query processing order (which differs from lexical writing order) [Documented] PostgreSQL SELECT documentation: https://www.postgresql.org/docs/current/sql-select.html:
WHEREvs.HAVING:WHEREfilters individual rows before grouping;HAVINGfilters aggregated groups afterGROUP BY.- Window functions:
OVER (PARTITION BY ... ORDER BY ...)computes rankings and running totals across related rows without collapsing them into a single summary row. NULLand three-valued logic: Standard equality or inequality comparisons againstNULLevaluate toUNKNOWNrather thanTRUEorFALSE(whereas predicates likeIS NULLhave dedicated semantics); as a consequence,x NOT IN (..., NULL)can never evaluate to true. [Documented] SQLite NULL handling guide: https://www.sqlite.org/nulls.html- Parameterized queries: Pass data values separately from the SQL statement template so the database driver binds them safely as literals, preventing SQL injection. [Documented] OWASP SQL Injection Prevention Cheat Sheet: https://cheatsheetseries.owasp.org/cheatsheets/SQL_Injection_Prevention_Cheat_Sheet.html
Runnable Example
Using an in-memory SQLite database populated with 5 fictional users and 7 fictional orders, we walk through constraints, aggregations, LEFT JOIN, CTEs + window functions, and three classic pitfalls. (First-draft execution record using Python's built-in sqlite3.)
"""SQL (real run, in-memory SQLite): table creation & constraints -> JOIN / GROUP BY / HAVING -> CTE & window functions
-> three classic pitfalls: NULL with NOT IN, COUNT(*) vs. COUNT(column), and SQL injection via string concatenation
(contrasted with parameterized queries). All data is fictional."""
import sqlite3
con = sqlite3.connect(":memory:"); cur = con.cursor()
con.execute("PRAGMA foreign_keys = ON")
print("SQLite", sqlite3.sqlite_version)
cur.executescript("""
CREATE TABLE users (user_id TEXT PRIMARY KEY, name TEXT NOT NULL, plan TEXT CHECK (plan IN ('free','pro','team')), referrer TEXT);
CREATE TABLE orders (order_id TEXT PRIMARY KEY, user_id TEXT REFERENCES users(user_id), amount REAL CHECK (amount > 0), status TEXT, created_at TEXT);
INSERT INTO users VALUES ('U1','Lin Xiaoxing','pro',NULL),('U2','Zhou He','free','U1'),('U3','Wu Bi','team','U1'),('U4','Zheng Ji','free',NULL),('U5','Wang Yun','pro','U3');
INSERT INTO orders VALUES
('O1','U1',365,'paid','2026-10-01'),('O2','U1',60,'paid','2026-10-03'),('O3','U2',30,'refunded','2026-10-02'),
('O4','U3',1299,'paid','2026-10-02'),('O5','U3',199,'paid','2026-10-05'),('O6','U5',365,'paid','2026-10-06'),('O7','U5',12,'pending','2026-10-07');
""")
def q(sql, *a):
cur.execute(sql, a); cols = [d[0] for d in cur.description]; rows = cur.fetchall()
print(" " + " | ".join(cols)); [print(" " + " | ".join(str(x) for x in r)) for r in rows]; return rows
try: cur.execute("INSERT INTO orders VALUES ('O8','U1',-5,'paid','2026-10-08')")
except sqlite3.IntegrityError as e: print("Constraint blocked negative amount:", e)
print("\n1. Paid revenue per subscription plan (JOIN + GROUP BY + HAVING)")
q("""SELECT u.plan, COUNT(*) AS n_orders, SUM(o.amount) AS revenue FROM orders o JOIN users u ON u.user_id = o.user_id
WHERE o.status = 'paid' GROUP BY u.plan HAVING SUM(o.amount) > 100 ORDER BY revenue DESC""")
print("\n2. LEFT JOIN: include users who have never placed an order")
q("""SELECT u.name, COUNT(o.order_id) AS n_orders, COALESCE(SUM(o.amount),0) AS total FROM users u LEFT JOIN orders o ON o.user_id = u.user_id
GROUP BY u.user_id ORDER BY total DESC""")
print("\n3. CTE + Window Functions: most recent order per user, and cumulative daily paid revenue")
q("""WITH ranked AS (SELECT user_id, order_id, created_at, ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY created_at DESC) AS rn FROM orders)
SELECT user_id, order_id, created_at FROM ranked WHERE rn = 1 ORDER BY user_id""")
q("""SELECT created_at, SUM(amount) AS day_rev, SUM(SUM(amount)) OVER (ORDER BY created_at) AS cum_rev
FROM orders WHERE status='paid' GROUP BY created_at""")
print("\n4. Pitfall 1: NOT IN with NULL -- find users who have never referred anyone")
r1 = q("SELECT name FROM users WHERE user_id NOT IN (SELECT referrer FROM users)")
r2 = q("SELECT name FROM users u WHERE NOT EXISTS (SELECT 1 FROM users x WHERE x.referrer = u.user_id)")
print(f" NOT IN returned {len(r1)} rows (subquery contains NULL, making predicate UNKNOWN); NOT EXISTS returned {len(r2)} rows")
print("\n5. Pitfall 2: COUNT(*) vs. COUNT(column)")
q("SELECT COUNT(*) AS all_rows, COUNT(referrer) AS non_null_referrer FROM users")
print("\n6. Pitfall 3: SQL Injection")
evil = "x' OR '1'='1"
cur.execute(f"SELECT COUNT(*) FROM orders WHERE user_id = '{evil}'"); print(" String concatenation: returned order count", cur.fetchone()[0], "(attacker sees all orders)")
cur.execute("SELECT COUNT(*) FROM orders WHERE user_id = ?", (evil,)); print(" Parameterized query: returned order count", cur.fetchone()[0])
First-draft retained output (not regenerated from the second-draft revision):
SQLite 3.53.1
Constraint blocked negative amount: CHECK constraint failed: amount > 0
1. Paid revenue per subscription plan (JOIN + GROUP BY + HAVING)
plan | n_orders | revenue
team | 2 | 1498.0
pro | 3 | 790.0
2. LEFT JOIN: include users who have never placed an order
name | n_orders | total
Wu Bi | 2 | 1498.0
Lin Xiaoxing | 2 | 425.0
Wang Yun | 2 | 377.0
Zhou He | 1 | 30.0
Zheng Ji | 0 | 0
3. CTE + Window Functions: most recent order per user, and cumulative daily paid revenue
user_id | order_id | created_at
U1 | O2 | 2026-10-03
U2 | O3 | 2026-10-02
U3 | O5 | 2026-10-05
U5 | O7 | 2026-10-07
created_at | day_rev | cum_rev
2026-10-01 | 365.0 | 365.0
2026-10-02 | 1299.0 | 1664.0
2026-10-03 | 60.0 | 1724.0
2026-10-05 | 199.0 | 1923.0
2026-10-06 | 365.0 | 2288.0
4. Pitfall 1: NOT IN with NULL -- find users who have never referred anyone
name
name
Zhou He
Zheng Ji
Wang Yun
NOT IN returned 0 rows (subquery contains NULL, making predicate UNKNOWN); NOT EXISTS returned 3 rows
5. Pitfall 2: COUNT(*) vs. COUNT(column)
all_rows | non_null_referrer
5 | 3
6. Pitfall 3: SQL Injection
String concatenation: returned order count 7 (attacker sees all orders)
Parameterized query: returned order count 0
- Constraints:
CHECK (amount > 0)rejects the negative amount at insert time; note that a SQLCHECKconstraint passes when its expression evaluates toUNKNOWN(NULL), so disallowingNULLrequires an explicitNOT NULLconstraint. The second-draft script also explicitly runsPRAGMA foreign_keys = ONto enforce foreign-key checks in SQLite. - 1. The
teamplan has 2 paid orders totaling 1,498.0, andprohas 3 totaling 790.0; thefreeplan's single order wasrefunded, soWHERE o.status = 'paid'filtered it out before grouping. - 2.
LEFT JOINpreserves "Zheng Ji" who never placed an order (0 orders, 0 total); notice we useCOUNT(o.order_id)rather thanCOUNT(*), becauseCOUNT(*)would count the joinedNULLrow as 1 order. - 3.
ROW_NUMBER()picks each user's latest order when timestamps have no ties (in production, add a deterministic tie-breaker column such asorder_id DESC);SUM(SUM(amount)) OVER (ORDER BY created_at)computes the running cumulative revenue up to 2,288.0. - 4. The
NOT IN+NULLtrap: Because thereferrercolumn containsNULL,user_id NOT IN (SELECT referrer FROM users)returns 0 rows;NOT EXISTSproperly returns the 3 users who never referred anyone (Zhou He, Zheng Ji, Wang Yun). The buggy query raises no error—it silently returns an empty set. - 5.
COUNT(*)counts all 5 rows, whereasCOUNT(referrer)counts only the 3 non-null values. - 6. SQL injection: Concatenating
x' OR '1'='1makes the predicate always true and exposes all 7 orders; the parameterized query treats the string literally and returns 0.
Common Pitfalls
- Using
NOT INon a subquery that might returnNULL: PreferNOT EXISTSor filter outNULLexplicitly inside the subquery. [Industry Consensus] - Building SQL via string interpolation: Always parameterize values, even in internal tools. Pay special attention when an LLM generates SQL: query parameter placeholders bind data literals only—they cannot bind table names, column names, sort directions, or full LLM-generated SQL statements; Text-to-SQL systems require AST validation, identifier allowlists, and strict database permissions.
- Using
SELECT *in production code: Schema changes can silently break positional consumers and pull unnecessary columns across the network. - Wrapping indexed columns in functions inside
WHEREclauses: Expressions likeWHERE YEAR(created_at) = 2026often prevent standard column B-tree index seeks unless an expression index or optimizer rewrite applies—always inspect the query plan (see k5.data.db-index). - Assuming all SQL dialects behave identically: Upsert syntax, date arithmetic, and string functions differ across SQLite, PostgreSQL, and MySQL (see k5.data.postgresql and k5.data.mysql).
Connection to AI Development
- Text-to-SQL and data-analysis Agents: when an LLM writes SQL queries, the host application must enforce read-only database roles, statement timeouts, and row limits, and validate results;
NULLsemantics and injection boundaries are among the most common failure points. - RAG metadata filtering, evaluation result aggregation, and token-cost dashboards all run on SQL under the hood (for analytical warehouses, see k5.data.warehouse).
Further Reading
- SQLite Window Functions documentation: https://www.sqlite.org/windowfunctions.html
- PostgreSQL Official Tutorial: https://www.postgresql.org/docs/current/tutorial.html
- Python
sqlite3documentation (parameter placeholders): https://docs.python.org/3/library/sqlite3.html
Second-Draft Scope & Self-Check
Logical query processing order defines relational result semantics, not the physical execution order chosen by the query optimizer. Standard equality/comparison operators against NULL yield UNKNOWN, whereas IS NULL and engine-specific null-safe operators follow distinct rules; CHECK constraints also do not reject NULL unless paired with NOT NULL. Parameter binding secures literal values only; dynamic identifiers (table/column names) and arbitrary LLM-generated SQL require separate sandboxing and validation.
Self-check: Does CHECK (amount > 0) by itself reject a NULL amount in standard SQL / SQLite?
Reference answer: No. In standard SQL and SQLite, a CHECK constraint fails only when the predicate evaluates to FALSE; an UNKNOWN result (from NULL > 0) passes the check, so you must also declare NOT NULL and verify your target database's rules.
Revisions & Verification in This Batch
- Enabled
PRAGMA foreign_keys = ONin SQLite and clarified the relationship betweenREFERENCESsyntax and runtime enforcement. - Qualified the claim about wrapping indexed columns in functions to note expression indexes and optimizer rewrites.
- Noted that window-function top-1 queries require a deterministic tie-breaking sort key when timestamps can collide.
The revised script was executed on a local CPU environment with exit code 0; see the execution log. Numbers reflect sample outputs rather than production performance guarantees.
Official Reference Verification (2026-10-15)
-
sqlite3 — DB-API 2.0 interface for SQLite databases — Python 3.15.0 documentation
-
SQLite CREATE TABLE constraints: A
CHECKexpression evaluating toNULLdoes not violate the constraint (useNOT NULLto forbid nulls); foreign-key enforcement must be explicitly enabled per connection.
Uncovered Areas & Follow-Ups
- Executed on SQLite only; outputs are not presented as a feature-by-feature compatibility proof for PostgreSQL or MySQL.
- In Text-to-SQL applications, read-only database credentials alone do not replace query resource limits or row-level data authorization.
Execution Scope for This Batch
2026-10-15: Passed. In-memory SQLite queries, foreign-key enforcement, NULL semantics, and parameter binding examples.
"First-draft retained output" preserves the original text and is not newly generated by the second-draft code; its original conclusions must be read in conjunction with the second-draft revisions and scope limitations.
Companion Code & Verification Materials