SQL describes the rows you want, not a step-by-step loop for finding them. AI retrieval uses ordinary SQL to enforce tenant, state, language, freshness, and authorization before or alongside vector ordering. Learn selection, joins, aggregation, common table expressions, parameters, and transactions so a framework cannot hide unsafe or inefficient database behavior.
Read the logical story as: rows come from FROM/JOIN, are filtered by WHERE, grouped, projected by SELECT, ordered, and limited. The optimizer may execute a different physical plan while preserving SQL semantics.
$1 and $2 are parameters supplied separately by a PostgreSQL client. Never concatenate untrusted text into SQL. Parameters protect values; dynamic table or column names require a fixed allowlist and safe identifier composition.
The application obtains $1 from authenticated server context, not request JSON. It validates $2 against the selected model and clamps $3 to an approved range.
Common table expressions improve readability and can define retrieval stages. They are not automatically faster; inspect the plan.
Use EXPLAIN (ANALYZE, BUFFERS) with non-sensitive test parameters. Compare returned row counts with a direct count and deliberately use a different tenant ID. Verify that no row crosses the boundary. Wrap mutation experiments in BEGIN and ROLLBACK.
Explain this SQL query clause by clause [paste]. Identify trust boundaries, parameters, possible duplicates, null behavior, and indexes worth testing. Rewrite it safely without changing semantics, then propose result and plan assertions.
Verification contract: Compare old and new results on fixtures, test cross-tenant denial, and inspect both plans before accepting the rewrite.