Quick revision
The short answer
Advanced SQL is the right tool when the database can do set-based work, such as aggregation, ranking, top-N and gap analysis, far more cheaply than shipping rows into Java; JPA stays the right tool for aggregate-oriented CRUD, and one service can use both with clear boundaries. Large SQL lives in versioned files or jOOQ, is tested against a real database with Testcontainers, follows readability rules (named CTEs, comments on business rules, plans in reviews), and is owned by a team with the skills to maintain it.
What to remember
In this answer, we set guidance for advanced SQL in Java services. The deciding question is the shape of the work: when the database can turn many rows into few through aggregation, ranking or top-N, SQL should do it; when we load and change aggregates, JPA fits. Large SQL lives in versioned files, jOOQ or views, is tested on a real database with Testcontainers, uses named CTEs, comments and plans in reviews, sits beside JPA behind clear boundaries, and always has an owning team with database skills.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
Advanced SQL is the right tool when the database can do set-based work, such as aggregation, ranking, top-N and gap analysis, far more cheaply than shipping rows into Java; JPA stays the right tool for aggregate-oriented CRUD, and one service can use both with clear boundaries. Large SQL lives in versioned files or jOOQ, is tested against a real database with Testcontainers, follows readability rules (named CTEs, comments on business rules, plans in reviews), and is owned by a team with the skills to maintain it.
Background to this question
Both extremes in this question are real and both are expensive. The 400-line report nobody understands becomes a liability the day its author leaves, and the team that bans SQL ends up loading two million rows into Java to compute a ranking the database could return in 200 milliseconds. A principal engineer is asked about this because the answer is a policy that many teams will follow for years. In this answer, we will see how to decide when SQL should do the work, how to keep large SQL maintainable in a Java codebase, which review practices make it readable, how JPA and SQL live side by side, and why ownership matters most.
1A Quick Recap: Set-Based Work Versus Row-by-Row Work
A relational database is built to work on sets. When we ask it to group 50 million order rows by customer and return the top 100, it reads the data where it lives, uses indexes and parallel workers, and sends back 100 rows. When we do the same job in Java through JPA, we pull rows over the network, build an entity object for each one, and then loop over them. The database version moves 100 rows; the Java version moves 50 million.
Advanced SQL means features such as CTEs (named subqueries), window functions (calculations across related rows that keep every row), LATERAL joins and recursive queries. They exist precisely so that this kind of work can stay in the database.
2When Advanced SQL Is the Right Tool
The guidance I would write starts from the shape of the work, not from personal taste. If the result is much smaller than the input, as with aggregation, ranking, top-N per group, running totals, deduplication or gap-and-island analysis, the database should do it. If the work is loading one aggregate, changing it according to business rules, and saving it, JPA is the better fit, because it gives us change tracking, optimistic locking and a domain model.
Notice that this is a measurable rule. A reviewer can ask how many rows the query reads and how many it returns. When that ratio is large, a set-based query is almost always cheaper, and the plan proves it.
| Work | Better tool | Why |
|---|---|---|
| Load, change and save one order | JPA | Change tracking, versioning, domain rules in Java |
| Top 10 products per region this week | SQL with window functions | Returns 10 rows per region instead of millions |
| Monthly revenue report | SQL with CTEs | Aggregation stays next to the data |
| Bulk update of 2 million prices | One SQL statement or batches | No entity per row |
| Find gaps in invoice numbers | SQL with LAG | One pass over an index |
| Simple lookups by id | JPA or Spring Data | Least code, cached by the persistence context |
3Keep Large SQL in Versioned, Tested Files
The 400-line report becomes unmaintainable partly because it lives as a Java string with concatenation, where no tool can format, highlight or check it. So the rule is that any query longer than a few lines lives in a place built for SQL. There are three good options. jOOQ generates Java classes from the schema, so queries are type-checked at compile time and a renamed column breaks the build instead of production. Spring's JdbcClient (Spring Framework 6.1 and later) works well with SQL kept in resource files. And a database view gives a stable name to a complex query that several services or reports use.
Every such query gets a test against a real database of the same engine and major version as production, which Testcontainers starts in a Docker container for the test run. An in-memory database such as H2 is not enough: it does not support many PostgreSQL features and gives different results for others.
The test is where business rules become explicit. How are ties ranked? Are refunds subtracted? A test with three hand-made rows answers those questions in a way that a reader of the SQL can trust. Sql.load is a placeholder for a few lines of resource-reading code; teams often use a small utility or Spring's ResourceLoader for it.
4Readability Practices for Heavy Queries
Long SQL is not the problem; unreadable SQL is. The guidance asks for named CTEs that each do one step (eligible_orders, spend_per_customer, ranked) so the query reads top-down like a story. Business rules get comments at the point where they are applied, for example '-- refunds within 30 days do not count as sales, per finance policy FIN-12'. Magic numbers become named parameters.
For queries that run on large tables, the pull request includes the EXPLAIN (ANALYZE, BUFFERS) output from a realistic dataset. That lets the reviewer check that the expected indexes are used and gives the next engineer a baseline when the query gets slower a year later.
5JPA and SQL in One Service
Banning raw SQL does not remove the need for it; it pushes it into @Query(nativeQuery = true) strings or, worse, into Java loops. So the guidance says plainly that mixing is fine. A typical service has its write side in JPA entities and repositories, and a read side for reports and lists written in SQL that returns records or DTOs directly, never managed entities.
The boundary matters for one technical reason: a bulk SQL UPDATE bypasses Hibernate's persistence context, so entities already loaded in the same transaction become stale. Keeping bulk SQL in separate transactions, or clearing the context after it, avoids that surprise. This is the same idea as CQRS, separating commands from queries, applied at a modest scale.
6Ownership: No Orphaned SQL
The last rule is about people. Every report query has an owning team listed in a CODEOWNERS file, and that team has at least two people comfortable with window functions, CTEs and plans. When a report has no owner, it is either adopted or retired.
A short example shows why this matters. A finance report with 30 CTEs was written by one contractor. A year later a schema change broke it at month end. With an owner, tests and comments, the fix takes an hour; without them, it takes three days of reverse engineering under pressure. The guidance exists to make the first outcome normal.
7Follow-up questions
How do you stop teams from writing everything in SQL once it is allowed?
By keeping the rule tied to the shape of the work. Writes to aggregates with business invariants stay in the domain model, because that is where the rules are tested and where optimistic locking protects them. Reviews ask which category a query falls into. If someone writes an UPDATE that encodes a business rule the domain model also enforces, we now have two versions of the rule, and the review should catch it.
Would you choose jOOQ or JdbcClient?
For a service with many complex queries that change with the schema, jOOQ's compile-time checks repay the build setup, and its licence terms depend on the database (open source databases such as PostgreSQL are covered by the free edition; check the current terms for commercial ones). For a service with a handful of reports, JdbcClient with SQL files and Testcontainers tests is simpler and has no extra dependency.
Where do views fit?
A view is useful when several consumers need the same complex query with the same meaning, because the definition then lives in one place and is versioned with the schema migrations. The cost is that the view's SQL is less visible to Java developers, so the same ownership and testing rules apply to it.
8Conclusion
In this answer, we set guidance for advanced SQL in Java services. The deciding question is the shape of the work: when the database can turn many rows into few through aggregation, ranking or top-N, SQL should do it; when we load and change aggregates, JPA fits. Large SQL lives in versioned files, jOOQ or views, is tested on a real database with Testcontainers, uses named CTEs, comments and plans in reviews, sits beside JPA behind clear boundaries, and always has an owning team with database skills.
Open with
I would base the guidance on the shape of the work rather than on preferences. If the result is much smaller than the data it reads, like aggregation, ranking, top N per group, running totals or gap analysis, the database should do it with CTEs and window functions, because moving millions of rows into Java to compute a hundred is slow and wasteful.
Then, if they want more
If we are loading an aggregate, applying business rules and saving it, JPA is the better fit for change tracking and optimistic locking. A service can do both: JPA for the write side, SQL returning DTOs for reports, with care around bulk updates and the persistence context.
To keep SQL maintainable, anything non-trivial lives in versioned SQL files used through JdbcClient, or in jOOQ for compile-time checking, or in views, and it is tested against the real engine with Testcontainers, not H2. Reviews of heavy queries require named CTEs for each step, comments on business rules, and an EXPLAIN ANALYZE on realistic data.
Finally, every report has an owning team with at least two people who can maintain it, so we never end up with orphaned 400-line queries.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Spring Framework 6
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- PostgreSQL documentation, The SQL Language
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Some teams write 400-line SQL reports with dozens of CTEs that nobody else understands...": https://scrivio-interview-library.netlify.app/databases/advanced-sql/9601c21cf0/