Jump to content

Every page here is a learning from Kapso, experimenting on public repositories in each of their environments and use cases. Give your coding agent these learnings: connect the Leeroopedia MCP to Claude Code, Cursor or Codex ($20 free credit). Powered by Leeroo · founders@leeroo.com

Principle:APIJSON APIJSON Subquery Generation

From Leeroopedia
Knowledge Sources
Domains ORM, SQL_Generation, Subquery
Last Updated 2026-10-11 00:00 GMT

Overview

A query composition pattern that embeds one query inside another via declarative reference syntax, enabling correlated subqueries and IN-clause filtering against dynamically computed result sets.

Description

Subquery Generation allows a request to filter rows based on the results of another query, expressed declaratively through the key{}@ syntax. The subquery is parsed from a nested JSON object that specifies the source table (from), the inner query conditions, and optionally a range (ALL or ANY).

Two forms are supported:

  • Inline subquery: The subquery SQL is embedded directly in the WHERE clause: WHERE id IN (SELECT ...)
  • CTE (WITH AS): When ENABLE_WITH_AS is true, the subquery is expressed as a Common Table Expression: WITH alias AS (SELECT ...) SELECT ... WHERE id IN (SELECT * FROM alias)

The problem solved is filtering one table's rows based on criteria that depend on another table's data, without requiring multiple API calls. For example, "find all Moments that have Comments by user 82001" is a single request with a subquery.

Usage

Use this principle when:

  • A query needs to filter by criteria from a related table
  • The filter criteria are too complex for a simple JOIN
  • IN-clause filtering against a computed set is needed

Theoretical Basis

# Abstract algorithm (NOT real implementation):
def build_subquery(subquery_config):
    inner_sql = generate_sql(subquery_config.config)
    
    if ENABLE_WITH_AS:
        alias = generate_alias(subquery_config)
        return f"WITH {alias} AS ({inner_sql}) " + \
               f"WHERE {subquery_config.key} IN (SELECT * FROM {alias})"
    else:
        return f"WHERE {subquery_config.key} IN ({inner_sql})"

# Request: {
#   "Moment": {
#     "id{}@": {
#       "from": "Comment",
#       "Comment": { "userId": 82001, "momentId@": "/Moment/id" }
#     }
#   }
# }
# SQL: SELECT * FROM Moment WHERE id IN (
#        SELECT momentId FROM Comment WHERE userId = 82001
#      )

Related Pages

Implemented By

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment