1

I would like to loop my query based on each element of an array. And I just want one result from each element out of the query.

Something like this:

array = ['a', 'b', 'c']

For i in array LOOP

SELECT *
FROM table_xyz
WHERE id = i
LIMIT 1

END LOOP;

So that I will have a table result like this:

id     | value
-------+--------
a      |  123
b      |  456
c      |  789
2
  • A cursor is more often than not a bad choice. It's a slow row-by-row processing whereas relational databases are optimized against doing set based operations. Commented Aug 26, 2019 at 5:26
  • @a_horse_with_no_name Thanks for the comments, I am kinda new to sql stuff. I am still trying to figuring those concepts here. Commented Aug 26, 2019 at 6:49

1 Answer 1

1

Why not get the results all at once:

    SELECT *
    FROM table_xyz
    WHERE id in ('a', 'b', 'c')
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks. Because I have thousands of id, and there are a lot of data from each id in the table. So it will cost a lot of time in the query and a lot of work to filter the result.
Well running thousands of separate queries will cost quite a bit of time as well. Without more understanding of the actual application, it's hard to make a suggestion, but you might want to consider putting your thousands of ids in a table (even a temporary table) and perform a JOIN with that table. getting a single results set is generally preferable to running thousands of queries.
make sense, I will give it a try. Thank you.
Or use the array directly: where id = any(array_variable)

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.