Search code examples
postgresqlcsvdeclare

PostgreSQL How to use a CSV in a query


Ok I am very new to postgres so bear with me. I have been using the string_agg function in postgres to get my CSV. I want to know how to use my CSV in a query. I did this in SQL server by using a DECLARE but as I have read there is not a way to DECLARE globally in postgres. Any help, documentation, examples would be greatly appreciated.


Solution

  • Ok, so based on your question and your comment. PostgreSQL has ARRAY type which fits nicely in SQL statements, so you can make an array from your CSV-string and use it in queries like:

    SELECT * FROM table WHERE record_id = ANY(string_to_array( string_agg , ','));
    

    Actually there is no need to use CSV at all. If you have such option change to use array_agg in the first place (instead of string_agg).

    Function string_to_array(text, delimiter) splits string into array with delimiter passed as an argument. Expression record_id = ANY( array ) returns TRUE when "any" of the array elements is equal to record_id and FALSE otherwise.