skip to Main Content

Im trying to get all unique values out of two rows in a databank as a list. Using postgresql and python.

I use this sql query:

SELECT DISTINCT from,to FROM database;

I get this output

 from | to 
------+-----
 a    | b
 d    | c
 b    | a

And in python as: [('a', 'b'), ('d', 'c'), ('b', 'a')]

But i want the result:["a", "b", "d", "c"]

I know i can use python to get this result but is there a direct sql query for that?

2

Answers


  1. Chosen as BEST ANSWER

    I found a solution:

    SELECT to AS value FROM database UNION SELECT from FROM database;
    

    In postgresql the UNION operator already restricts to distinct elements if ALL is not added. The alias is used to ensure that the output table column is named "value".


  2. You can make an union and select unique elements from there:

    SELECT DISTINCT value
    FROM (
        SELECT from AS value FROM database
        UNION ALL
        SELECT to AS value FROM database
    );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search