Blog/Stop hiding my SQL

Stop hiding my SQL

Somewhere along the way, hiding SQL became the default definition of a good ORM. That deserves a second look, since SQL was rarely the part that caused the pain.

January 20, 2026SQL4 min read

The second query language problem

To hide SQL, an ORM has to give you something else to write: JPQL, a criteria builder, or a fluent DSL that models joins and predicates as method calls. A DSL is a good thing to have, and ST/ORM has one. Trouble starts when the DSL is the only safe path and SQL is treated as the unsafe escape hatch, because that path always ends somewhere. An aggregate, a window function, a recursive CTE, or a database-specific feature the abstraction never modeled sends you to a native query. You end up writing SQL anyway, as a raw string with no type safety, since the safe path only covered the cases that did not need it.

SQL was never the weak point

SQL is declarative, portable enough for real work, and understood by almost every backend engineer who works near a relational database. It is one of the most durable interfaces in our field. What made hand-written database code fragile was everything around the SQL: column names as bare strings that no compiler checks, parameters concatenated into the query by hand, result sets mapped to objects by index one brittle line at a time, and mappings that drift silently when the query changes. That surrounding code is the part worth fixing, and the SQL can stay as it is.

Type the SQL, do not bury it

ST/ORM's SQL templates, the piece that started the whole project, let you write real SQL with type-safe interpolation and automatic result mapping. Column references go through the generated metamodel, so a renamed field, a broken path, or a wrong type fails at compile time instead of at runtime. Interpolated values become bind parameters and are never concatenated into the SQL text. Results map to plain data classes and records. A window function is the kind of query a DSL will not express for you, and written as a template it keeps all of that safety:

ReportService.kt Kotlin · ST/ORM
1
2
3
4
5
6
7
8
// Only RANK() OVER is raw SQL; the columns and table are typed
data class RankedCity(val name: String, val rank: Long)

val ranked = orm.query { """
    SELECT ${City_.name}, RANK() OVER (ORDER BY ${City_.population} DESC)
    FROM ${City::class}
    WHERE ${City_.country} = $country
""" }.resultList<RankedCity>()

For the boring, high-volume queries there is a concise DSL, so a find-by-id does not need any SQL. Use the DSL for the common queries and a template when SQL is the clearest way to express the job. Neither one is a fallback for the other, and everything your database can do stays one line away.