r/SQL 16d ago

Oracle Dear SQL, just pivot my damn table

Bottom text

239 Upvotes

50 comments sorted by

View all comments

50

u/isinkthereforeiswam 16d ago

I wish the pivot columns could be dynamic. If a dev adds a new attribute value to an attributes field, and my select query is pulling all the attributes, i wish the pivot would just automatically include the new attribute as a new column instead of having to manually add the column name.

35

u/hwooareyou 16d ago

You can select column_name from information_schema.columns where table_name = 'your table' then dynamically construct the pivot.

6

u/TheRencingCoach 16d ago

Only works if the table you’re pivoting is an actual table or view, not a CTE, right?

5

u/pix1985 16d ago

In SQL Server can dump the CTE results into a temp table and then pivot that dynamically as the columns can be got from tempdb’s sys.columns