0

I multiply result rows of a SELECT with CROSS JOIN generate_series(1, max). My query is like:

select id, name
from person
CROSS JOIN generate_series(1, 4)
where <condition>;

I have this result:

id name
1 name1
1 name1
1 name1
1 name1
2 name2
2 name2
2 name2
2 name2
3 name3
3 name3
3 name3
3 name3

I want the result like this:

id name
1 name1
2 name2
3 name3
1 name1
2 name2
3 name3
1 name1
2 name2
3 name3
1 name1
2 name2
3 name3

Is that possible?

Erwin Brandstetter
186k28 gold badges463 silver badges636 bronze badges
asked May 1, 2023 at 21:13

1 Answer 1

0

Sure, ORDER BY expressions do not have to be listed in the SELECT list.
Order by the generated value, then by whatever else you want to order by:

SELECT p.id, p.name
FROM person p
CROSS JOIN generate_series(1, 4) g(g)
WHERE p.id < 4 -- or whatever
ORDER BY g.g, p.id; -- !!!

Or, with minimal syntax (less safe against ambiguous identifiers):

SELECT id, name
FROM person, generate_series(1, 4) g
WHERE id < 4 -- or whatever
ORDER BY g, id; -- !!!
answered May 1, 2023 at 22:03
1
  • Just thought I'd mention "ORDER BY expressions do not have to be listed in the SELECT list" except when DISTINCT is used (which it isn't here) Commented May 1, 2023 at 23:20

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.