I have a table and I want to select all unique values of all attributes in one query.
For example table Person
with 3 columns name, age, city
.
Example:
Name | age | city |
---|---|---|
Alex | 34 | New York |
Leo | 34 | London |
Roy | 20 | London |
Alex | 28 | Moscow |
Mike | 36 | London |
And I want to have a result with unique values of every attribute
Name | age | city |
---|---|---|
Alex | 20 | New York |
Leo | 28 | London |
Roy | 34 | Moscow |
36 |
Is it possible to do this query?
I tried to make some queries with DISTINCT
and UNION
, but the result with always a multiplication of rows.
2
Answers
This is not how relational databases work, but sometimes you got to do what you got to do.
You can do:
One option is to aggregate into array, then unnest those arrays:
I would expect this to be quite slow if you really have many distinct values ("millions"), but if you only expect very few distinct values ("hundreds" or "thousands") , then this might be OK.