Search code examples
sqlpostgresqldistinctset-returning-functions

Return column name and distinct values


Say I have a simple table in postgres as the following:

+--------+--------+----------+
|  Car   |  Pet   |   Name   |
+--------+--------+----------+
| BMW    |  Dog   |   Sam    |
| Honda  |  Cat   |   Mary   |
| Toyota |  Dog   |   Sam    |
| ...    |  ...   |   ...    |

I would like to run a sql query that could return the column name in the first column and unique values in the second column. For example:

+--------+--------+
|  Col   |  Vals  |
+--------+--------+
| Car    |  BMW   |
| Car    | Toyota |
| Car    | Honda  |
| Pet    |  Dog   |
| Pet    |  Cat   |
| Name   |  Sam   |
| Name   |  Mary  |
| ...    |  ...   |

I found a bit of code that can be used to return all of the unique values from multiple fields into one column:

-- Query 4b.  (104 ms, 128 ms)
select distinct unnest( array_agg(a)||
                        array_agg(b)||
                        array_agg(c)||
                        array_agg(d) )
from t ;

But I don't understand the code well enough to know how to append the column name into another column.

I also found a query that can return the column names in a table. Maybe a sub-query of this in combination with the "Query 4b" shown above?


Solution

  • SQL Fiddle

    SELECT distinct
           unnest(array['car', 'pet', 'name']) AS col,
           unnest(array[car, pet, name]) AS vals
    FROM t
    order by col