Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unpivot in Potgresql

How can I unpivot in Postgresql without using UNION? I have more than 100 columns, and I am looking for a neat way to do it.

Given table:

id    c1      c2      c3
1      X       Y       Z
2      A       B       C
3      Y       C       Z

Desired table:

id   col
1     X
1     Y
1     Z
2     A
2     B
2     C
3     Y
3     C
3     Z
like image 221
geek2000 Avatar asked Aug 30 '17 01:08

geek2000


People also ask

What does Unpivot do in SQL?

Rotates a table by transforming columns into rows. UNPIVOT is a relational operator that accepts two columns (from a table or subquery), along with a list of columns, and generates a row for each column specified in the list. In a query, it is specified in the FROM clause after the table name or subquery.

What is Unpivot data?

An unpivot transformation is one way to transform data from a short/wide to a tall/skinny format. When the data types of source columns differ, the varying data is converted to a common data type so the source data can be part of one single column in the new data set.

Can we Unpivot in SQL?

Conventionally we can say that Pivot operator converts the rows data of the table into the column data. The Unpivot operator does the opposite that is it transform the column based data into rows.

Why do we Unpivot data?

You might want to unpivot data, sometimes called flattening the data, to put it in a matrix format so that all similar values are in one column. This is necessary, for example, to create a chart or a report.


1 Answers

Use jsonb functions:

select id, value as col
from my_table
cross join jsonb_each_text(to_jsonb(my_table))
where key <> 'id';

 id | value 
----+-------
  1 | X
  1 | Y
  1 | Z
  2 | A
  2 | B
  2 | C
  3 | Y
  3 | C
  3 | Z
(9 rows)

Db<>Fiddle.


In Postgres 9.3 or 9.4 use to_json() and json_each_text().

In versions 9.1 or 9.2 install hstore:

create extension if not exists hstore;

select id, value as col
from my_table
cross join each(hstore(my_table))
where key <> 'id';
like image 167
klin Avatar answered Sep 29 '22 07:09

klin