SQL Pivot Generator (Rows to Columns)
Turn rows into columns without hand-writing a dozen aggregates. Enter your table, the column(s) that identify each output row, the category column to spread across the page, and the value to aggregate — the generator writes the pivot query for you in three flavours: a PostgreSQL FILTER (WHERE ...) query, a portable CASE WHEN form that runs on MySQL, SQL Server and SQLite, and the classic PostgreSQL crosstab() call with the tablefunc setup it needs. It also produces the reverse unpivot (columns back to rows) with LATERAL VALUES. Everything runs in your browser; nothing is uploaded.
Do more than sql pivot generator (rows to columns) — meet Chat2DB
Chat2DB is an AI-powered SQL client for Windows, macOS and Linux. Write SQL in natural language, format and optimize queries automatically, and manage MySQL, PostgreSQL, Oracle and 20+ other databases in one workspace.
How to use
- Enter the table, the row identifier column(s), the category column, and the list of category values that should become columns.
- Pick the value column and aggregate (SUM, COUNT, AVG, MIN, MAX) and choose PostgreSQL FILTER or the portable CASE dialect.
- Copy the generated pivot query, the crosstab() version, or the unpivot statement for the reverse direction.
Frequently asked questions
How do I pivot rows to columns in SQL?
Use one conditional aggregate per output column: SELECT region, SUM(amount) FILTER (WHERE quarter = 'Q1') AS q1, SUM(amount) FILTER (WHERE quarter = 'Q2') AS q2 FROM sales GROUP BY region. On databases without FILTER, write SUM(CASE WHEN quarter = 'Q1' THEN amount END) instead. Each aggregate only 'sees' rows from its category, so one GROUP BY row becomes one output row with a column per category.
What is crosstab() in PostgreSQL and when should I use it?
crosstab() comes from the tablefunc extension (CREATE EXTENSION tablefunc) and returns a pivoted record set from a 'row, category, value' query. Prefer the two-argument form, which takes an explicit category list so columns stay aligned even when data is missing. It keeps the query short when you have many categories, but the FILTER/CASE approach is usually easier to read, needs no extension, and supports multiple row columns and several aggregates at once.
Can SQL pivot with a dynamic list of columns?
Not directly — SQL requires every output column to be known before the query runs, so the category list must be hard-coded. For dynamic pivots, first run SELECT DISTINCT category FROM t, then build the pivot statement in application code or in a plpgsql function with EXECUTE. Chat2DB's AI SQL editor can also write and run these pivot queries against your live schema — download it at https://chat2db.ai/download or use the web version at https://app.chat2db.ai.
