← Files SQL CopilotARCHIVED FILE
references/correctness-and-grain.md
1.44 KB · Dec 2, 2026 · 18:35 UTC
# SQL correctness: meaning before syntax ## Logical grain checklist Write down one row per **what** for each table, intermediate CTE and final output. Determine which columns are unique at that grain. If an order-level amount is joined to item rows, the amount repeats for each item. Do not fix a business model with a cosmetic DISTINCT. ## Invariants worth checking - `COUNT(*)` vs `COUNT(DISTINCT business_key)` at each stage (only where a unique key is expected). - Sum of monetary measures before/after dimensional joins; reconcile at same currency/precision. - `LEFT JOIN` with right-side filter in WHERE can drop unmatched left rows. - `COUNT(*)` counts all rows; `COUNT(column)` ignores NULL values. - `NOT IN` against NULL-containing subqueries can yield unexpected unknown comparisons; consider `NOT EXISTS` with understood correlation semantics. - Window ranking is defined by partition plus ordering; ties and final tie-breaker matter. - Columns in aggregate outputs need consistent grouping; avoid mixing daily and monthly measures inadvertently. ## Precision and dates Use decimal types for exact financial amounts when appropriate. Explicitly define rounding and order of operations. Convert instants to reporting zones only with a documented business rule. Prefer comparisons against `[start,end)` for timestamps instead of `BETWEEN` on midnight boundaries. Deliver the minimal semantic correction and queries that can falsify the suspected root cause.
SHA-256: b2bad989f2888f484506b3bfc71f548a7d1f5988cd7cb6a346f69bd9ad351445