Quick revision
The short answer
Complex SQL should live in versioned files or a type-safe DSL such as jOOQ rather than in concatenated Java strings, so it is reviewed, diffed and tested like code. It should be tested against the real database engine with Testcontainers, using fixtures that cover edge cases such as NULLs and empty groups, with plan checks on the few queries that matter most. Analytical SQL belongs in a warehouse or transformation layer owned by data engineering, OLTP SQL stays simple, each schema has one owning service, and we invest in SQL skills and reviewers, because complex SQL is often the best tool when it is managed well.
What to remember
In this answer, we saw that the problem with thousand-line SQL in Java strings is treatment, not SQL itself. We put complex queries in versioned .sql files or jOOQ, tested them on the real engine with Testcontainers and edge-case fixtures, with plan checks on the critical few, moved analytical SQL to a warehouse owned by data engineering, gave each schema one owning service, and invested in SQL reviewers and skills, rolling the change out by touching the worst queries first and measuring the effect.
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.
Complex SQL should live in versioned files or a type-safe DSL such as jOOQ rather than in concatenated Java strings, so it is reviewed, diffed and tested like code. It should be tested against the real database engine with Testcontainers, using fixtures that cover edge cases such as NULLs and empty groups, with plan checks on the few queries that matter most. Analytical SQL belongs in a warehouse or transformation layer owned by data engineering, OLTP SQL stays simple, each schema has one owning service, and we invest in SQL skills and reviewers, because complex SQL is often the best tool when it is managed well.
Why this question is asked
Thousand-line queries in Java strings are not a sign that SQL was the wrong choice. They are a sign that SQL was treated as text rather than code: no single home, no tests, no owner. The cost shows up as reports nobody dares to change, regressions after database upgrades, and incidents when one service changes a shared table. Interviewers ask this at principal level to see whether we can set a strategy that is realistic for hundreds of services, not a rewrite. In this answer, we will look at what goes wrong today, then decide where SQL should live, how it is tested, where analytical SQL should run, who owns schemas, and how to roll the change out over time.
1What Goes Wrong With SQL in Java Strings
When a query is built by concatenating strings in Java, several things break at once. Reviews show a diff of string fragments, so nobody can read the final query. The query cannot be run as written in a SQL console, so tuning it means reconstructing it first. Dynamic parts are easy to get wrong, from a missing space to SQL injection if a value is concatenated instead of bound. And nothing checks it until it runs in production, so a renamed column or a NULL nobody expected surfaces as an incident.
The other half of the problem is placement. Many of the thousand-line queries are reports: aggregates over months of data, joined across domains, often reading tables that belong to other services. They run against the OLTP databases that serve customers, competing with checkout for CPU and I/O, and they couple services to each other's schemas. Fixing the code style alone would not fix that.
2Where Complex SQL Should Live
The rule I would set is that any non-trivial query exists in one readable, versioned place. There are two good options. Static queries live in .sql files in the service's resources, loaded by name and executed with bind parameters, so the file can be opened and run in a console and the diff is the query. Dynamic queries, where filters and sort orders vary, use a type-safe DSL such as jOOQ, generated from the real schema, so a renamed column fails compilation instead of production.
JPA and Spring Data remain fine for the simple CRUD and lookups that make up most OLTP access. The point is not to ban any tool, but to make sure that the complex queries have a home that reviewers can read and tools can check. Long queries should also be broken into named CTEs with a comment per step, which costs nothing on PostgreSQL 12 and later because single-use CTEs are inlined.
3How Complex SQL Is Tested
SQL must be tested on the same engine and major version that runs in production, because NULL handling, collation, date arithmetic and planner behaviour differ between engines, and an in-memory database can make a wrong query pass. Testcontainers starts a real PostgreSQL or MySQL in a container for the test run, migrations create the schema, and fixtures insert data. The fixtures are where the value is: each important query gets cases for NULLs in optional columns, empty groups, ties, time zone boundaries and duplicates, the cases that break reports in practice.
For the handful of queries that are critical for performance, we add plan checks: a test or a scheduled job that runs EXPLAIN on a staging database with production-like volumes and fails if, for example, a sequential scan appears on a large table or the estimated cost jumps. Plans depend on data and statistics, so these checks belong on realistic data, not on tiny fixtures, and they should cover a small, curated list rather than every query. Before each database upgrade, the same list is replayed on the new version.
4Where Analytical SQL Should Run
The biggest structural change is to move reporting and analytical SQL out of the OLTP services. Those queries scan months of data and join across domains; they belong in a warehouse or lakehouse, fed by change data capture or batch extracts, and built with a transformation tool where models are SQL files with tests, documentation and lineage. Data engineering owns that layer and its reliability. The services keep the SQL that serves requests, which should be short, indexed and predictable.
This also solves the coupling problem. Today a report in service A reads service B's tables directly, so B cannot change its schema without breaking A. With a warehouse, B publishes its data through a defined pipeline, and the report reads the warehouse model. Moving everything at once is unrealistic, so we start with the heaviest and most fragile reports, measured by runtime and incidents.
- OLTP servicesshort indexed queries; JPA, jOOQ or .sql files; tested with Testcontainers
- Service-owned schemasone owner per schema; changes through migrations and contracts
- Data pipelineCDC or batch extracts, no direct cross-service reads
- Warehouse modelsanalytical SQL as tested, versioned models owned by data engineering
- Reports and BIread the warehouse, not the OLTP databases
5 layers, from the top down. Step through them one at a time.
5Ownership, Skills and the Rollout
Every schema gets one owning service and team. Other services do not read its tables directly; they use an API, events or the warehouse. Changes to a shared legacy schema, until it is split, go through a lightweight review with the teams that depend on it. This is what makes it safe to refactor SQL at all, because the owner knows every consumer.
Finally, people. Complex SQL is often the best tool: a well-written window query can replace hundreds of lines of Java and run far faster. So the strategy is not 'less SQL', it is 'SQL done well'. That means a small group of strong SQL reviewers across the organisation, short internal training on plans, NULLs and window functions, and a style guide. The rollout follows the usual pattern: new code follows the rules from day one, existing queries move when they are changed or when they cause an incident, and we track the share of complex queries with tests and the number of SQL-related incidents each quarter to see whether it works.
6Follow-up questions
Why not replace complex SQL with Java code over simple queries?
Because it usually moves the work to the wrong place. Joining and aggregating in Java means transferring far more rows over the network, holding them in memory, and reimplementing what the database does with indexes and optimised algorithms. It also tends to hide the same bugs, such as NULL handling, in less visible code. Java is the right place for business rules; set-based data work belongs in SQL.
Should we standardise on jOOQ everywhere?
Not necessarily. jOOQ is strong for dynamic, complex queries, and its code generation catches schema drift at compile time. For CRUD, Spring Data JPA is simpler, and for static reports, a .sql file is the most readable. A standard that allows these three, with a clear rule for when to use each, is easier to adopt than forcing one tool on hundreds of services. Note that jOOQ's commercial databases need a paid licence, which matters for the decision.
How do you get teams to adopt this without a big programme?
By making the right way the easy way: a shared library for loading .sql files, a template project with Testcontainers set up, and examples from real services. Then we pick the five queries that caused the most incidents, move them first, and publish the result. Teams adopt practices that visibly solved someone else's problem far faster than ones announced in a document.
7Conclusion
In this answer, we saw that the problem with thousand-line SQL in Java strings is treatment, not SQL itself. We put complex queries in versioned .sql files or jOOQ, tested them on the real engine with Testcontainers and edge-case fixtures, with plan checks on the critical few, moved analytical SQL to a warehouse owned by data engineering, gave each schema one owning service, and invested in SQL reviewers and skills, rolling the change out by touching the worst queries first and measuring the effect.
Open with
I would treat SQL as code rather than text. First, where it lives: complex static queries go into versioned .sql files in the service, loaded by name and run with bind parameters, so a reviewer sees the real query and can paste it into a console.
Then, if they want more
Dynamic queries use a type-safe DSL like jOOQ generated from the schema, so a renamed column breaks the build, not production. JPA stays for simple CRUD. Long queries get split into named CTEs with comments.
Second, testing: every important query runs in tests against the real engine and version with Testcontainers, never an in-memory substitute, and fixtures deliberately include NULLs, empty groups, ties and time zone edges. For a short list of performance-critical queries, we check plans on production-like data in staging and replay them before each database upgrade.
Third, placement: most thousand-line queries are analytics running on OLTP databases and reading other services' tables. Those should move to a warehouse fed by change data capture, built as tested SQL models owned by data engineering, so OLTP SQL stays short and indexed. Fourth, ownership: each schema has one owning service, and others use APIs, events or the warehouse.
Finally, skills: complex SQL is often the right tool, so I would build a group of strong SQL reviewers and some training. I would roll it out incrementally, worst queries first, and track tested queries and SQL incidents per quarter.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- PostgreSQL 12
- 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 "Your company's SQL has grown into thousand-line queries with nested derived tables and...": https://scrivio-interview-library.netlify.app/databases/sql-joins-and-subqueries/bdf63087c0/