Search code examples
sqlpostgresqlselectresultset

How to select multiple row in postgresql?


I can give a result set consisting of a single value, say 1, as follows:

SELECT 1 as column;

and it gives me the result set:

column
------
  1

But I have a list of such values represented as a string (1, 4, 7, ...) and I need to produce the following result set:

column
------
  1
  4
  7
  .
  .
  .

I tried SELECT * FROM (1, 4, 7) but it didn't work. I also tried to SELECT 1, 4, 7 but it produces the following result set:

col1   col2    col3
 1       4      7

Which was not what I was looking for.


Solution

  • If those are constant values, you can use the values clause:

    select * 
    from (
       values (1), (4), (7)
    ) as t(id);
    

    If your values are inside a string literal, you can use this:

    select *
    from unnest(string_to_array('1,2,3,4', ',')) as id;