Create a temp table, loop, add data, select from it? “Query has no destination for result data”

All we need is an easy explanation of the problem, so here it is.

I am creating a temp table, and am fetching data from multiple tables and inserting data into it. When I try to get the data back from the table I get an error:

[42601] ERROR: query has no destination for result data
Hint: If you want to discard the results of a SELECT, use PERFORM instead.
        sampleproductId   varchar;
        productIds        text[] := array [
        tId              varchar;
        DECLARE result  jsonb;
        DECLARE resultS jsonb[];
       CREATE TEMP TABLE IF NOT EXISTS product_temp_mapping
            accountid      int,
            productUID      varchar,
            sampleproductId text
        FOREACH sampleproductId IN ARRAY productIds
                tId := (select id
                        from product.product
                        where uid = sampleproductId);
                INSERT into product_temp_mapping (accountid, productUID, sampleproductId)
                select accountid, tId, sampleproductId
                from product.accountproductmap
                where productId = cast(tId as int);
            END LOOP;
        select * from product_temp_mapping;
    end ;

Is this the right way to do it? This is the first time I am doing something with a temp table.

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

When I try to get the data back from the table I get an error.

That’s because you cannot return anything from a DO statement. You would need a function where you define the return type in the RETURNS clause. (But you still wouldn’t need a temporary table.)
Plus, PL/pgSQL does not allow SELECT without a target.

But you don’t need any of this for the example. A plain query does it:

SELECT a.accountid::int, AS product_uid, a.sampleproductId::text
FROM   product.product p
JOIN   product.accountproductmap a ON a.productId =
WHERE  p.uid = ANY ('{abc1, abc2}'::text[]);

Some of the casts are probably unnecessary.
You might wrap it into an SQL function (PL/pgSQL not needed for this). See:

Aside: use legal, lower-case identifiers! See:

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply