Unexpected behavior of UNION ALL operator in Redshift SQL statement

0

I need to union together the results of two queries - we'll call them Query A and Query B. Their outputs have matching column structures and data types, so nothing special should need to be done to put the results together; there are no duplicates to remove, so I am using a UNION ALL. When I run each query independently in the AWS Query Editor, they return results normally. When I put the queries together with UNION ALL and run that full query in the AWS Query Editor, it returns results normally. However, I am functionally running the full query within a stored procedure by assembling the SQL in a string and using EXECUTE, and this is where the problem starts happening. I have other stored procedures following a similar code pattern that work just fine, including some that include queries with UNION/UNION ALL operators in them, so this problem behavior is unexpected.

Query A is a pretty basic query taking the values from a single table and doing some simple aggregations. Query B is a bit more complex, and it includes a simple correlated subquery that limits the results to rows with an ID that exists in another table. If you take Query A and use a UNION ALL with it, it works fine. If you take Query B and use a UNION ALL with it, even just to tack on hardcoded values (e.g. SELECT 1, 'a', 'b'), you get the following error: "This type of correlated subquery pattern is not supported due to internal error." Again, it works just fine if you run the "unioned" query in the query editor directly, but as soon as you try to execute it within a stored procedure, you get the error.

I have worked around this by putting Query B's results into a temporary table before doing the union, but this is obviously inefficient compared to querying the data directly. Especially when using a UNION ALL, I would not expect the correlated subquery in Query B to have any impact on the ability to produce a result, even more so because the full query runs just fine in the editor. But is this behavior somehow expected in this context?

asked 15 days ago88 views
No Answers

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions