Principle:APIJSON APIJSON Subquery Generation
| 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
# )