25

I would like to combine two select queries with UNION.
How can I use the result from the first SELECT in the second SELECT?

(SELECT carto_id_key FROM table1
    WHERE tag_id = 16)
UNION 
(SELECT * FROM table2
    WHERE carto_id_key = <the carto_id result from above> )
4
  • what do you actually want to achieve, this can be with a simple JOIN or a Subquery (if you just wish to get the required details), also the columns both of your queries dont match !! Commented Apr 6, 2013 at 10:14
  • I want to get all the records in table2 that meet the condition of the first SELECT Commented Apr 6, 2013 at 10:26
  • if that's the only requirement, read postgresql.org/docs/8.3/static/tutorial-join.html Commented Apr 6, 2013 at 10:31
  • After looking at that documentation I found the best solution to be: SELECT * FROM tabl1 INNER JOIN table2 ON (table1. carto_id_key = table2. carto_id_key) WHERE table2.tag_id = 16 thanks for the help Commented Apr 6, 2013 at 14:20

2 Answers 2

35

Use a CTE to reuse the result from a subquery in more than one SELECT.

WITH cte AS (SELECT carto_id_key FROM table1 WHERE tag_id = 16)

SELECT carto_id_key
FROM   cte

UNION ALL
SELECT t2.some_other_id_key
FROM   cte
JOIN   table2 t2 ON t2.carto_id_key = ctex.carto_id_key

You most probably want UNION ALL instead of UNION. Doesn't exclude duplicates and is faster this way.

Sign up to request clarification or add additional context in comments.

1 Comment

Nice. I just tried this and found that for UNION ALL to work, both of the SELECT statements had to return the same number of columns, with the same data types.
0

This is simpler solution to just have a normal select and combine result using WITH :

WITH combinedResult AS (
SELECT
    (SELECT COUNT(t1) FROM table1 t1) as table1Count,
    (SELECT COUNT(t2) FROM table2 t2) AS table2Count 
                       )
SELECT table1Count, table2Count FROM combinedResult;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.