Quick revision
The short answer
Building the SQL string from SELECT DISTINCT category risks SQL injection, because column names cannot be bind parameters, and it produces a result whose shape changes every week, which breaks typed DTOs, statement caching and consumers, and can hit PostgreSQL's 1,600 column limit. The better design is to return long format (product, category, amount) with a plain GROUP BY and pivot in Java with Collectors.groupingBy, or in the BI tool; if SQL must pivot, generate the column list in a reviewed step with format('%I') or quote_ident against a whitelist, and cap the number of columns.
What to remember
In this answer, we saw that building pivot SQL from SELECT DISTINCT category pastes data into SQL text, where bind parameters cannot help, creating a second-order injection risk, and that a result whose columns change weekly breaks DTOs, caching and consumers and can hit the 1,600 column limit. We recommended returning long format from SQL and pivoting in Java with Collectors.groupingBy or in the BI tool, and, where SQL must pivot, generating columns in a reviewed step with format('%I'), a whitelist and a cap.
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.
Building the SQL string from SELECT DISTINCT category risks SQL injection, because column names cannot be bind parameters, and it produces a result whose shape changes every week, which breaks typed DTOs, statement caching and consumers, and can hit PostgreSQL's 1,600 column limit. The better design is to return long format (product, category, amount) with a plain GROUP BY and pivot in Java with Collectors.groupingBy, or in the BI tool; if SQL must pivot, generate the column list in a reviewed step with format('%I') or quote_ident against a whitelist, and cap the number of columns.
Why this question is asked
Dynamic pivots look like a small convenience: query the categories, glue them into a SELECT, done. In a code review, this pattern deserves a pause, because it mixes data into SQL text and makes the API's shape depend on whatever rows exist today. Interviewers ask it to see whether we notice both the security risk and the design smell, and whether we can offer something better. In this answer, we will look at the proposal, the injection risk, the problems of a changing result shape, the long format with a pivot in Java, and how to do it safely in SQL when we must.
1The Proposal and Why It Is Tempting
The developer's plan is to read the current categories, then build a conditional aggregation query with one SUM(CASE ...) column per category, and run it.
It is tempting because SQL needs to know its columns in advance, and the categories are only known at run time. Generating the SQL seems like the only way. But the code above has two serious problems before we even talk about design.
2Risk 1: SQL Injection Through Data
Bind parameters, the ? or :name placeholders, protect values, but they cannot stand for identifiers such as column names or aliases. So the category names are concatenated into the SQL text, twice: once as a string literal and once as a column alias. Categories are data, and data comes from people. A category called Kids' Toys breaks the query with a syntax error. One crafted by someone with access to the product admin screen, such as x' THEN 0 END) AS a FROM sales; DROP TABLE sales; --, turns into executable SQL.
This is second-order injection: the dangerous input entered the database safely earlier and becomes dangerous when it is read back and pasted into SQL. Code reviewers miss it because there is no request parameter in sight. The rule is that identifiers built from data must be quoted with a safe function, such as PostgreSQL's quote_ident or format('%I'), or matched against a whitelist, and values must still go through bind parameters.
3Risk 2: A Result Whose Shape Changes
Even if the SQL were safe, the result has a different set of columns whenever a category is added. Typed DTOs cannot represent it, so the code falls back to Map<String, Object>, and every consumer must handle columns it has never seen. Front ends and exports that expect fixed columns break or silently drop the new ones. Prepared statement caches in the driver and the database see a new SQL text each week, so they cannot reuse plans.
There are hard limits too: a PostgreSQL table or result row can have at most 1,600 columns, and long before that, a report with 400 category columns is unreadable. Finally, the pivot is computed at the database, the most expensive and least scalable part of the system, for what is really a presentation concern.
| Approach | Safety | Stable API shape | Where the pivot runs |
|---|---|---|---|
| Dynamic SQL from DISTINCT | injection risk | no, changes weekly | database |
| Long format + pivot in Java | bind parameters only | yes, fixed rows | application |
| Long format + BI or spreadsheet | bind parameters only | yes | BI tool |
| Reviewed generated SQL, quoted, capped | safe if quoted | versioned | database |
4The Better Design: Long Format, Pivot in Java
SQL is very good at grouping, so we let it group, and we return a fixed, long shape: one row per product and category. The query has constant text and bind parameters only. Then the service pivots in memory, which for a report of a few thousand cells is trivial.
Notice that the API can now return the long cells, or a structure with a categories list and rows of values in that order, both of which have a fixed schema. The front end or the BI tool, Excel, Tableau or Power BI, pivots the long format natively and lets users choose which categories to show. That is often the cleanest answer of all: give the tool long data and let it do the presentation.
5When SQL Must Pivot
Sometimes a pivot must exist in the database, for example as a view that an external tool reads. Then we generate the column list in a controlled step: a reviewed migration or a scheduled job that rebuilds the view, not code that runs per request. PostgreSQL's format with %I quotes identifiers safely and %L quotes literals.
The LIMIT caps the number of columns, the job validates names against an approved list, and the generated view is versioned, so consumers see a deliberate schema change rather than a surprise. It is more work than the original proposal, which is exactly why the Java pivot is usually the better choice.
6Follow-up questions
How would you stream a large pivot to a CSV without loading it all in memory?
First fetch the category list, which gives the CSV header. Then run the long-format query ordered by product and category, and stream it with a JdbcTemplate RowCallbackHandler or a Stream from JdbcClient with a fetch size set; in PostgreSQL the driver only uses a cursor when autocommit is off, so run it in a read-only transaction. Accumulate the cells of the current product in a small map, and when the product changes, write that row to the output stream with the categories in header order and missing cells as 0. Memory then holds one product at a time, whatever the size of the report.
Is quote_ident enough to make dynamic SQL safe?
It makes an identifier safe to embed, because it wraps it in double quotes and escapes embedded quotes. But values used in the same SQL still need quote_literal or bind parameters, and we still need limits on the number of columns and a review of the result shape. Safety of the text is only one of the problems.
Why not have the database return JSON instead of columns?
That is a reasonable middle ground: jsonb_object_agg(category, amount) per product returns one fixed column holding a map, so the SQL text is constant and safe. The consumer still has to handle changing keys, but the schema of the response is stable.
7Conclusion
In this answer, we saw that building pivot SQL from SELECT DISTINCT category pastes data into SQL text, where bind parameters cannot help, creating a second-order injection risk, and that a result whose columns change weekly breaks DTOs, caching and consumers and can hit the 1,600 column limit. We recommended returning long format from SQL and pivoting in Java with Collectors.groupingBy or in the BI tool, and, where SQL must pivot, generating columns in a reviewed step with format('%I'), a whitelist and a cap.
Open with
I see two kinds of risk. The first is security. Column names and aliases cannot be bind parameters, so this code concatenates category names into the SQL text.
Then, if they want more
Categories are data that people enter, so a name with a quote breaks the query, and a crafted name becomes SQL injection; it is second-order injection, which is easy to miss in review because no request parameter is involved.
If identifiers ever come from data, they must be quoted with quote_ident or format with percent I, or matched against a whitelist. The second is design.
The result shape changes every week, so typed DTOs and fixed-column consumers break, the code ends up passing maps around, statement caching does not help, and PostgreSQL caps a row at 1,600 columns, long before which the report is unreadable anyway.
I would recommend returning long format from SQL: product, category and summed amount, with a constant query and bind parameters. Then pivot in Java with Collectors.groupingBy into a map per product, plus a sorted set of categories for the column order, or simply give the long data to the BI tool or spreadsheet, which pivots natively.
If a pivot really must live in SQL, for example a view for an external tool, I would generate it in a reviewed, versioned job with format percent I and percent L, validate names against an approved list, and cap the number of columns.
About this answer
- Last updated
- 12 November 2026
- 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 "Product managers want a pivot report where columns are product categories, but...": https://scrivio-interview-library.netlify.app/databases/sql-coding-problems/7a600386ab/