Polymorphic SQL: A Unified Query Approach
- Polymorphic SQL is a query framework that maintains SQL's declarative core across varying schemas, models, and temporal regimes, ensuring data portability.
- It leverages principal typing, multi-model generalizations, and temporal semantics to enable consistent and adaptable query evaluation.
- Its approaches promote cross-dialect execution and syntax-independent optimization, leading to improved performance and logical equivalence in diverse SQL engines.
Polymorphic SQL denotes a family of approaches that preserve SQL’s declarative core while allowing the same query language, or the same logical query intent, to remain meaningful across changes in schema, data model, temporal regime, backend dialect, or surface formalism. Across the literature, this includes principal typing for relational algebra, SQL generalization to JSON and semi-structured values, unified querying over relational, key-value, document, and graph models, time-varying relational semantics for stream processing, cross-dialect execution-equivalence evaluation, and syntax-independent optimization for SQL/PGQ [0106035], (Ong et al., 2014, Begoli et al., 2019, Rotschield et al., 12 May 2025, Perlitz et al., 8 May 2026).
1. Scope and dimensions
The term is not used uniformly. In the literature summarized here, it is best understood as an umbrella notion for several distinct forms of SQL-level invariance. Sometimes the invariant is a type-correct relational expression that remains valid under many schema assignments. Sometimes it is a query language that spans tables and semi-structured documents. Sometimes it is one relational semantics across batch and streaming inputs. Elsewhere it is the preservation of query correctness across SQL dialects, or the preservation of execution quality across alternative notations such as relational SQL and graph-pattern syntax.
| Dimension | Representative mechanism | Representative work |
|---|---|---|
| Schema and typing | Principal types over attribute sets | [0106035] |
| Semi-structured and multi-model data | SQL generalization to JSON, bags, graphs, and nested values | (Ong et al., 2014, Yan et al., 2020) |
| Temporal behavior | Time-varying relations, event time, materialization control | (Begoli et al., 2019) |
| Dialect and backend portability | Dual execution and normalized result comparison | (Perlitz et al., 8 May 2026) |
| Surface-form polymorphism | SQL/PGQ with syntax-independent optimization goals | (Rotschield et al., 12 May 2025) |
This breadth matters because “polymorphism” in SQL research rarely means only one thing. A language-theoretic account emphasizes principal typing and schema-parametricity. Systems papers more often emphasize cross-model reuse of the SELECT–FROM–WHERE idiom, portability across engines, or optimizer behavior that should depend on query semantics rather than on the notation chosen to express them.
2. Schema polymorphism, typing, and the relational core
The most direct language-theoretic formulation appears in "Polymorphic type inference for the relational algebra" [0106035]. That work gives “a polymorphic account of the relational algebra,” introduces “type formulas” specifically tuned for relational algebra expressions, and presents an algorithm that computes the “principal” type for a given expression. Its abstract defines the principal type as a formula that specifies “all assignments of types (sets of attributes) to relation names” under which a relational algebra expression is well-typed, together with the output type produced under each such assignment. In this sense, polymorphic SQL is the extension of relational typing from one fixed catalog to a family of admissible schemas.
This notion is narrower, and more formal, than generic schema awareness. "FHE-SQL: Fully Homomorphic Encrypted SQL Database" explicitly emphasizes “schema-aware, type-safe definitions suitable for relational data management,” and its operators are defined generically over encrypted values of appropriate types, but the same paper also states that it does not introduce polymorphic typing, type variables, overloaded generic query combinators, or a formal notion of relational polymorphism in the programming-languages sense (Tseng et al., 17 Oct 2025). The distinction is important. Schema-aware execution, typed encrypted operators, and generic AST evaluation are related to polymorphic SQL, but they are not identical to principal typing or schema-parametric query semantics.
A common misconception is therefore to equate any generic or reusable SQL mechanism with polymorphism proper. The literature distinguishes at least three levels: well-typedness under varying attribute sets, schema-parametric execution disciplines, and backend-agnostic or model-agnostic runtime behavior. Only the first directly matches the classical meaning of polymorphism in type theory.
3. Semi-structured and multi-model generalization
One major research trajectory extends SQL across data models rather than merely across schemas. "The SQL++ Query Language: Configurable, Unifying and Semi-structured" defines SQL++ as backwards compatible with SQL, applicable to both JSON-native stores and SQL databases, and powered by a semi-structured data model that is a superset of both JSON and the SQL data model (Ong et al., 2014). Its value grammar includes null, missing, primitive and enriched scalars, tuples, arrays, and bags; its FROM clause can range over arbitrary collections and tuple attributes; and its SELECT ELEMENT and SELECT ATTRIBUTE forms allow arbitrary values and variable-width tuples as outputs. Equally important, SQL++ is configurable: path navigation, equality, null/missing behavior, coercions, and related edge cases are exposed as semantic options, allowing the language to morph into the semantics of SQL, MongoDB, Cassandra CQL, Couchbase N1QL, and AsterixDB AQL.
"Multi-SQL: An extensible multi-model data query language" pursues a related objective from a different design angle (Yan et al., 2020). It supports relational, key-value, document, and graph models, and introduces TRIPLE = \langle ITEM\_NAME, ITEM\_TYPE, ITEM\_CONSTRAINT \rangle as a common structural unit. The language keeps SQL-style top-level constructs such as SELECT, WHERE, and JOIN, but partitions predicates into basic filters shared across models and characteristic filters specific to a model, notably MATCH for nested document structure and PATH for graph traversal. Its JOIN ... RULE ... WITH ... form is explicitly heterogeneous: a join can consume objects from different models and can construct an output object in yet another shape, including nested document-like results.
A more foundational mathematical account appears in "Polystore Mathematics of Relational Algebra" (Jananthan et al., 2017). That work models relations as associative arrays and uses associative-array operations as a common substrate for SQL sets and multisets, graph structures, and matrix-oriented systems. Projection, rename, union, intersection, selection, theta join, extended projection, and aggregation are expressed as array operations over a semiring-valued domain. The paper proves familiar relational laws in this common representation, including
and
This suggests that one form of polymorphic SQL is not merely a broad surface syntax, but a shared algebraic intermediate semantics capable of spanning relations, sparse tables, graphs, and matrices.
4. Temporal polymorphism
A separate line of work treats SQL as polymorphic over temporal behavior. "One SQL to Rule Them All" argues that batch tables, mutable tables, continuous views, and streams can all be understood through the single semantic foundation of the time-varying relation, or TVR (Begoli et al., 2019). A TVR “can also be treated as a function, mapping each point in time to a static relation,” which allows standard relational operators to lift pointwise over time. Under this view, the same SQL query can be interpreted uniformly over finite historical data, continuously arriving unbounded data, and mixed settings.
The paper’s second pillar is explicit event time semantics. An event time column is a distinguished TIMESTAMP column with an associated watermark, and “a watermark is a monotonic function from processing time to event time” (Begoli et al., 2019). This lets completeness be reasoned about in event-time space rather than in arrival order. The proposal then adds event-time table-valued functions such as Tumble(data, timecol, dur, [offset]) and Hop(data, timecol, dur, hopsize, [offset]), which return ordinary relations augmented with interval columns wstart and wend. Grouping remains ordinary GROUP BY over columns; window assignment is pushed into TVFs instead of being treated as a separate streaming-only operator family.
The third pillar is materialization control. EMIT STREAM asks for a changelog view of the result TVR; EMIT AFTER WATERMARK materializes only complete rows; EMIT AFTER DELAY d materializes periodically; and combined forms support periodic emission plus final-on-completeness behavior (Begoli et al., 2019). The significance is that the relational core of the query does not change when moving among batch execution, live streaming, replayed logs, continuously updated outputs, and final-only outputs. In this sense, temporal polymorphism means that SQL is invariant across bounded and unbounded inputs, table and stream views, and multiple output materialization regimes.
5. Dialectal and cross-schema portability
Another meaning of polymorphic SQL concerns backend portability. "PolySQL: Scaling Text-to-SQL Evaluation Across SQL Dialects via Automated Backend Isomorphism" shows that SQLite-centered evaluation is an unreliable proxy for target-dialect behavior (Perlitz et al., 8 May 2026). Its core method avoids query transpilation: the source gold query is executed on the source backend, the model’s target-dialect query is executed on the migrated target backend, and normalized execution outputs are compared. The result comparator performs structural alignment, schema homogenization, and type-aware value comparison. Empirically, the paper reports 100% query coverage and higher fidelity than transpilation-based alternatives; across 16 models and shared examples, SQLite and target dialects have only weak per-query agreement, with average Cohen’s of 0.39, and there is a 10.1% average accuracy drop from SQLite to enterprise dialects. The dominant source of cross-dialect degradation is logical rather than syntactic: 61.2% of gap errors are Filtering/Logic, while 7.7% are Dialect Syntax (Perlitz et al., 8 May 2026).
This is a strong claim about backend polymorphism. A system that appears correct on one engine is not necessarily correct, or even similarly correct, on PostgreSQL, MySQL, Snowflake, BigQuery, or ClickHouse. Dialect robustness is therefore not reducible to lexical transpilation. It depends on backend semantics, typing, grouping strictness, function repertoires, and output normalization.
"SQL-Exchange: Transforming SQL Queries Across Domains" addresses a different portability problem: preserving query structure while adapting SQL across schemas and domains (Daviran et al., 9 Aug 2025). It formalizes the source-side inputs , , and schema , together with target schema , and seeks target-side outputs and such that the target question is meaningful, the target SQL is correct for that question, and source and target SQL share the same logical structure abstracting away from table names, column names, and constants. Its mechanism is template-guided abstraction: the source query is converted into a placeholder skeleton, then re-instantiated against the target schema and sample data. The paper reports that SQL-Exchange improves structural alignment by +18% to +53.53%, result yield by +14.7% to +21.7%, and meaningful questions by +5.3% to +13.3%; when a source query contains a JOIN, SQL-Exchange retains joins in over 90% of cases across all settings (Daviran et al., 9 Aug 2025). A plausible implication is that schema portability and dialect portability are adjacent but distinct forms of polymorphic SQL: one preserves logic across naming and domain changes, the other across execution semantics of different engines.
6. Optimization and execution polymorphism
A further, and increasingly central, interpretation concerns optimization. "Towards Cross-Model Efficiency in SQL/PGQ" studies SQL/PGQ, a standard that integrates graph querying into relational systems, allowing users to define property graph views over relational tables and then query them with graph patterns whose results are still relational (Rotschield et al., 12 May 2025). The paper’s key claim is that in such a multi-formalism environment, performance should depend on the semantics of the query and the best available execution strategy, not on whether the user wrote SQL joins or graph-pattern syntax.
The technical bridge between the two sides is explicit. Bounded graph patterns can often be rewritten into ordinary SQL joins without recursion, while unbounded graph patterns can be rewritten as recursive SQL (Rotschield et al., 12 May 2025). This means SQL and PGQ are not merely coexisting syntaxes; they overlap semantically. The difficulty is that current systems often optimize them through separate internal paths. In DuckDB with DuckPGQ, traversal-heavy SQL/PGQ frequently outperforms recursive SQL, whereas in Spanner, bounded SQL consistently outperforms SQL/PGQ, suggesting stronger optimization for traditional joins.
| System and case | SQL runtime | SQL/PGQ runtime |
|---|---|---|
| DuckDB, Q4, size 50 | 982 ms |
23.6 ms |
| DuckDB, Q5, size 150 | 12,420 ms |
55.5 ms |
| Spanner, Q2, size 50 | 29 ms |
177 ms |
| Spanner, Q3, size 50 | 44 ms |
1,020 ms |
The same paper reports graph-creation overheads that differ by orders of magnitude: DuckDB graph creation is roughly 0.2, 0.4, and 0.5 ms, while Spanner is around 4,700–4,870 ms and Neo4j around 4,293–4,668 ms (Rotschield et al., 12 May 2025). These numbers make the central point concrete. Syntax polymorphism without optimizer polymorphism exposes users to performance cliffs. The paper therefore argues for “a holistic optimization, where the system internally decides on the best algorithms regardless of whether queries are written in SQL or as graph patterns,” including internal rewriting at the intermediate-representation or query-plan level.
7. Limits, misconceptions, and open problems
The literature does not support a single, closed definition of polymorphic SQL. Instead, it identifies a set of partially overlapping ambitions. Some are formal and static, as in principal typing over sets of attributes [0106035]. Others are semantic and systems-oriented, as in SQL++ configuration over null, missing, path failures, and coercions (Ong et al., 2014). Others are operational, as in SQL/PGQ’s demand for syntax-independent planning (Rotschield et al., 12 May 2025). This plurality is productive, but it also means that claims about “polymorphic SQL” should be interpreted relative to the dimension under discussion.
Several boundaries recur. SQL/PGQ does not imply universal bidirectional translation: the paper explicitly states that recursive SQL is strictly more expressive than SQL/PGQ in general, and also notes that query equivalence testing is generally undecidable (Rotschield et al., 12 May 2025). The temporal account based on TVRs, event time, and EMIT controls is powerful, but the same work calls for more rigorous formal definitions of watermarks and materialization semantics, and leaves late-data policy, custom windows, and state evolution as open issues (Begoli et al., 2019). PolySQL’s backend-isomorphism method is strong on the shared capability region of source and target backends, but it does not benchmark dialect-native features absent from SQLite-born datasets (Perlitz et al., 8 May 2026). Multi-SQL offers an extensible architecture and a two-level execution strategy, yet its published case is stronger as language design than as large-scale empirical validation (Yan et al., 2020).
A final misconception is that any generic execution framework is automatically a polymorphic SQL language. The encrypted execution model of FHE-SQL is highly relevant to schema-aware, type-safe, generic SQL processing, but the paper itself is explicit that it is not about polymorphic SQL in the programming-languages sense (Tseng et al., 17 Oct 2025). This suggests that future work will likely need to combine several threads now studied separately: principal typing, configurable semantics for irregular and nested data, backend portability, cross-model algebra, and optimizer architectures that choose physical strategies independent of surface syntax.
Taken together, these works define polymorphic SQL less as a single language than as a research agenda: one in which SQL is expected to survive variation in schema, model, time, dialect, and notation while preserving correctness, compositionality, and execution quality.