107 words
1 minute
Using unnest() to use a comma-separated string as the input to an IN query

Using unnest() to use a comma-separated string as the input to an IN query#

django-sql-dashboard lets you define a SQL query plus one or more text inputs that the user can provide in order to execute the query.

I wanted the user to provide a comma-separated list of IDs which I would then use as input to a WHERE column IN ... query.

I figured out how to do that using the unnest() function and regexp_split_to_array:

select * from report where id in (select unnest(regexp_split_to_array(%(ids)s, ',')))

The ids string passed to this query is split on commas and used for the IN clause.

Here’s a simple demo of how unnest() works:

select unnest(regexp_split_to_array('1,2,3', ','))

Output:

unnest
1
2
3
Using unnest() to use a comma-separated string as the input to an IN query
https://mranv.pages.dev/posts/using-unnest-to-use-a-comma-separated-string-as-the-input-to-an-in-query/
Author
Anubhav Gain
Published at
2024-03-31
License
CC BY-NC-SA 4.0