3

I want to print 4 times the same row in PostgreSQL, how to achieve that ?

Table : mytable

Id   |  name
------------
 1   |  foo
 2   |  bar
 3   |  zzz

I want something like

Select 4x mytable.* from mytable where id=1

And the result should be

Id   |  name
------------
 1   |  foo
 1   |  foo
 1   |  foo
 1   |  foo
3
  • 2
    Do it in the presentation layer. Commented Apr 4, 2017 at 9:22
  • possible duplicate of stackoverflow.com/questions/4097266/… Commented Apr 4, 2017 at 9:24
  • @Geek Junior you can do it with sub queries Commented Apr 4, 2017 at 9:26

4 Answers 4

13

You can cross join against generate_series(1,4), which will return a table containing the numbers 1 to 4:

SELECT mytable.*
FROM mytable 
CROSS JOIN generate_series(1,4) as x
WHERE id=1

For each row in your original result set, there will be one copy with 1 next to it, one with 2, and so on.

Sign up to request clarification or add additional context in comments.

1 Comment

Exactly what i was looking for, i red a lot about generate_series but could not figure out how to use it across my big query. Just tested it ! works fine. Thanks
2

you can use generate_series.

sample:

t=# create table so48 (i int,n text);
CREATE TABLE
t=# insert into so48 select 1,'a';
INSERT 0 1
t=# insert into so48 select 2,'b';
INSERT 0 1

select:

t=# with s as (select generate_series(1,4,1) g) select so48.* from so48 join s on true where i = 1;
 i | n
---+---
 1 | a
 1 | a
 1 | a
 1 | a
(4 rows)

1 Comment

A little bit complicated according to the multiple joins in my original query, i tried to make it simple in my example
0

use union all

Select mytable.* from mytable where id=1
union all Select mytable.* from mytable where id=1
union all Select mytable.* from mytable where id=1
union all Select mytable.* from mytable where id=1

1 Comment

useful but it will make my query bigger !
-1

Cross join should do the job

Select 4x mytable.* from mytable where id=1 
cross join
(select 1 from dual union all
select 1 from dual union all
select 1 from dual union all
select 1 from dual )

2 Comments

it is postgres no oracle
The approach makes sense though, just need to remove the from dual (and the 4x that has been copied from the pseudocode in the question).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.