This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: postgres-17-sql-json-table-optimization-invariants

Postgres 17 SQL/JSON JSON_TABLE Optimization & Memory Invariants

Enforces strict query planning invariants and memory bounds when projecting JSON/JSONB payloads into relational tabular formats using Postgres 17 JSON_TABLE. Mandates precise SQL/JSON path evaluation, typed column projection with strict error handling, and the prevention of unindexed full-table nested scans or memory bloat caused by unbounded path expansion. Guarantees queries retain index-driven scan paths and work_mem compliance.

Prohibited Anti-Pattern: Unbounded JSON_TABLE Path Projections with Implicit Type Casts and Silent Error Fallbacks

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Postgres 17 SQL/JSON JSON_TABLE Optimization & Memory Invariants - Enforces strict query planning invariants and memory bounds when projecting JSON/JSONB payloads into relational tabular formats using Postgres 17 JSON_TABLE. Mandates precise SQL/JSON path evaluation, typed column projection with strict error handling, and the prevention of unindexed full-table nested scans or memory bloat caused by unbounded path expansion. Guarantees queries retain index-driven scan paths and work_mem compliance.
globs: src/db/**/*.sql, src/repositories/**/*.ts, src/services/**/*.ts, src/infrastructure/database/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/postgres-17-sql-json-table-optimization-invariants"
---

# Postgres 17 SQL/JSON JSON_TABLE Optimization & Memory Invariants

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unbounded JSON_TABLE Path Projections with Implicit Type Casts and Silent Error Fallbacks

## System Constraints
You are a Principal Database Architect and Performance Engineer enforcing Postgres 17 SQL/JSON (ISO/IEC 9075-2) JSON_TABLE invariants. You must prevent memory exhaustion from runaway lateral joins, ensure strict handling of type mismatches via ERROR ON ERROR clauses, and guarantee that path projections align with functional GIN/BTREE indexes to prevent full relation sequential scans.

## Strict Guidelines
- Engineers MUST ALWAYS declare an explicit 'ERROR ON ERROR' or validated default clause in JSON_TABLE column mappings to prevent silent NULL conversions that mask schema drift and data corruption.
- Engineers MUST NOT evaluate unbounded or recursive JSONPath wildcard expressions (e.g., '$.**') inside JSON_TABLE path contexts, as this disables cost-based index estimates and leads to catastrophic execution time.
- Queries projecting scalar data for join conditions MUST match the data type and collation of corresponding relational indexes to ensure Nested Loop / Hash Join execution plans instead of sequential materialization.
- Code MUST pass pre-filtered JSON subsets or combine JSON_TABLE with GIN/jsonb_path_ops WHERE filters to eliminate non-matching documents before JSON_TABLE projection expansion.
- Queries MUST NOT use JSON_TABLE inside unbounded LATERAL joins without explicit row-count fences (e.g., LIMIT or strict existence filters) to prevent work_mem exhaustion.

## Bad vs Good Implementations
### Unbounded JSON_TABLE Projection vs Index-Backed Filtered Projection

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Implicit NULL ON ERROR masks malformed numerical payloads, and evaluating JSON_TABLE before filtering on amount forces the planner to deconstruct every JSON document in the tenant before applying the filter, causing high CPU and memory overhead.
```typescript
import { sql } from 'kysely';
import { db } from './database';

// ANTI-PATTERN: Wildcard path scan with default NULL ON ERROR,
// bypassing GIN indexes and forcing full table scan and excessive memory allocation.
export async function getTenantOrders(tenantId: string) {
  return await sql`
    SELECT o.id, jt.item_id, jt.amount
    FROM orders o,
    JSON_TABLE(
      o.payload,
      '$.items[*]'
      COLUMNS (
        item_id text PATH '$.id',
        amount numeric PATH '$.amount'
      )
    ) AS jt
    WHERE o.tenant_id = ${tenantId}
      AND jt.amount > 100;
  `.execute(db);
}
```

#### Production Standard (Correct)
> **Standard**: The 'strict' JSONPath mode alongside 'ERROR ON ERROR' guarantees deterministic execution and schema validation. The GIN index predicate (@?) filters candidates prior to JSON_TABLE row expansion, drastically reducing planner memory and execution cost.
```typescript
import { sql } from 'kysely';
import { db } from './database';

// PRODUCTION FIX: Targets GIN-indexed path with strict typed validation,
// explicitly fenced by jsonb existence operators to prevent unnecessary deserialization.
export async function getTenantOrders(tenantId: string) {
  return await sql`
    SELECT o.id, jt.item_id, jt.amount
    FROM orders o
    CROSS JOIN JSON_TABLE(
      o.payload,
      'strict $.items[*]' PASSING o.payload
      COLUMNS (
        item_id uuid PATH '$.id' ERROR ON ERROR,
        amount numeric(12, 2) PATH '$.amount' ERROR ON ERROR
      )
    ) AS jt
    WHERE o.tenant_id = ${tenantId}
      AND o.payload @? '$.items[*] ? (@.amount > 100)'
      AND jt.amount > 100;
  `.execute(db);
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Postgres 17 SQL/JSON JSON_TABLE Optimization & Memory Invariants

Postgres 17 SQL/JSON JSON_TABLE Optimization & Memory Invariants defines an industrial-grade behavioral standard for backend engineering. Enforces strict query planning invariants and memory bounds when projecting JSON/JSONB payloads into relational tabular formats using Postgres 17 JSON_TABLE. Mandates precise SQL/JSON path evaluation, typed column projection with strict error handling, and the prevention of unindexed full-table nested scans or memory bloat caused by unbounded path expansion. Guarantees queries retain index-driven scan paths and work_mem compliance. Modern software architectures require strict adherence to deterministic patterns to guarantee high availability, maintainability, and zero security vulnerabilities.

Framework Paradigm Shift & Drift MechanicsLLMs are trained on millions of open-source repositories containing outdated code, legacy idioms, and unpatched antipatterns. When coding assistants generate implementations for this stack, they default to common statistical tokens: Unbounded JSON_TABLE Path Projections with Implicit Type Casts and Silent Error Fallbacks Without an explicit system instruction file, developers spend hours debugging silent failures.
Failure Modes & Production Blast Radius

Hazard Analysis: What Breaks Without This Rule

The following failure modes have been cataloged from hundreds of hours of production code reviews where AI assistants produced non-compliant implementations:

Failure ModeAI Symptom (The Anti-Pattern)SeverityProduction Impact & Remedy
AI Hallucination & Deprecation DriftUnbounded JSON_TABLE Path Projections with Implicit Type Casts and Silent Error FallbacksCritical
Violating this industrial standard introduces regression bugs, security risks, and unexpected runtime failures in production.
Enforce explicit behavioral system directives across all AI coding assistants in your repository.
Silent Architecture InconsistencyAI assistants produce mixed paradigms across files, creating fragmented codebase conventions.Medium
Increases cognitive load during code reviews and leads to maintenance debt across engineering teams.
Pin project conventions in .cursor/rules, CLAUDE.md, and AGENTS.md so all team agents follow identical guardrails.
Architectural Directives in Detail

Step-by-Step Production Directives

Each rule constraint below is injected into the AI agent's system prompt to establish deterministic boundaries:

1

Engineers MUST ALWAYS declare an explicit 'ERROR ON ERROR' or validated default clause in JSON_TABLE column mappings to prevent silent NULL conversions that mask schema drift and data corruption.

Engineers MUST ALWAYS declare an explicit 'ERROR ON ERROR' or validated default clause in JSON_TABLE column mappings to prevent silent NULL conversions that mask schema drift and data corruption.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
2

Engineers MUST NOT evaluate unbounded or recursive JSONPath wildcard expressions (e.g., '$.**') inside JSON_TABLE path contexts, as this disables cost-based index estimates and leads to catastrophic execution time.

Engineers MUST NOT evaluate unbounded or recursive JSONPath wildcard expressions (e.g., '$.**') inside JSON_TABLE path contexts, as this disables cost-based index estimates and leads to catastrophic execution time.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
3

Queries projecting scalar data for join conditions MUST match the data type and collation of corresponding relational indexes to ensure Nested Loop / Hash Join execution plans instead of sequential materialization.

Queries projecting scalar data for join conditions MUST match the data type and collation of corresponding relational indexes to ensure Nested Loop / Hash Join execution plans instead of sequential materialization.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
4

Code MUST pass pre-filtered JSON subsets or combine JSON_TABLE with GIN/jsonb_path_ops WHERE filters to eliminate non-matching documents before JSON_TABLE projection expansion.

Code MUST pass pre-filtered JSON subsets or combine JSON_TABLE with GIN/jsonb_path_ops WHERE filters to eliminate non-matching documents before JSON_TABLE projection expansion.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
5

Queries MUST NOT use JSON_TABLE inside unbounded LATERAL joins without explicit row-count fences (e.g., LIMIT or strict existence filters) to prevent work_mem exhaustion.

Queries MUST NOT use JSON_TABLE inside unbounded LATERAL joins without explicit row-count fences (e.g., LIMIT or strict existence filters) to prevent work_mem exhaustion.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is Postgres 17 SQL/JSON JSON_TABLE Optimization & Memory Invariants critical for AI coding assistants?

Enforces strict query planning invariants and memory bounds when projecting JSON/JSONB payloads into relational tabular formats using Postgres 17 JSON_TABLE. Mandates precise SQL/JSON path evaluation, typed column projection with strict error handling, and the prevention of unindexed full-table nested scans or memory bloat caused by unbounded path expansion. Guarantees queries retain index-driven scan paths and work_mem compliance. Without explicit behavioral boundaries, AI coding assistants (Cursor, Claude Code, Windsurf, Codex) rely on training data averages, which frequently produce deprecated, inefficient, or vulnerable code patterns.

Q:How does adopting this rule prevent AI hallucinations?

This rule explicitly declares what the AI must avoid (Unbounded JSON_TABLE Path Projections with Implicit Type Casts and Silent Error Fallbacks) and prescribes verified positive examples. Grounding the LLM with negative and positive pairs eliminates guesswork.

Q:Which AI coding environments are supported?

This specification is multi-platform compatible: Cursor (.cursor/rules/*.mdc & .cursorrules), Anthropic Claude Code (CLAUDE.md), Windsurf (.windsurfrules), Codex / Cline (AGENTS.md), and GitHub Copilot (.github/copilot-instructions.md).

Q:Can I combine this rule with other technology stacks?

Yes. Use the Interactive Stack Builder or download an Agent Pack to merge this rule with other frontend, backend, database, security, and DevOps rules without syntax collision.

Open Specification · CC BY 4.0·Free for Personal, Team & Commercial In-Repo Use

Citation & Open Source Attribution Guidelines

This specification is licensed under Creative Commons Attribution 4.0 International (CC BY 4.0). You are completely free to adapt and share this rule in your workspace. If citing, including in public AI benchmark datasets, or redistributing, attribution to AgentRules.org is required.

1 Rule in Stack

Postgres