Formatting IDs for Efficient IN Clause Usage with PostgreSQL Regular Expressions and String Functions
To format these ids to work with your id in ('x','y') query, you can convert the string of ids to an array and use that array directly instead of an IN clause.
Here are a few ways to do this:
**Method 1: Using regexp_split_to_array()
SELECT *
FROM the_table
WHERE id = ANY (regexp_split_to_array('32563 32653 32741 33213 539489 546607 546608 546608 547768', '\s+')::int[]);
**Method 2: Using string_to_array()
If you are sure that there is exactly one space between the numbers, you can use the more efficient (faster) string_to_array() function:
SELECT *
FROM the_table
WHERE id = ANY (string_to_array('32563 32653 32741 33213 539489 546607 546608 546608 547768', ' ')::int[]);
In both cases, the ANY clause will return all rows where the value of the id column matches any value in the array.
Last modified on 2023-11-30