Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

122
Views
UNION based on just one column

I want to UNION two tables based on a single column.

Assume that, I have a table called t1:

Id |  Name  
------------
1  |    A   
2  |    B  
3  |    C   

And a second table called t2:

Id |  Name  
------------
1  |    B   
3  |    B  
5  |    B

I want to UNION them like this:

SELECT * FROM T1
UNION
SELECT * FROM T2
BASED ON ID 

And I expect a result like:

Id |  Name  
------------
1  |    A   
2  |    B  
3  |    C 
5  |    B

If IDs are equal then pick the row from the first table:

Actually, I am working with tables which have 20+ columns. These tables are for demonstration.

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

One option uses not exists:

select id, name
from t1
union all
select id, name
from t2
where not exists (select 1 from t1 where t1.id = t2.id)

You can also use conditional aggregation - although this is more cumbersome, and probably a little less efficient:

select
    id,
    coalesce(
        max(case when which = 1 then name end),
        max(case when which = 2 then name end)
    ) name
from (
    select id, name, 1 which from t1
    union all
    select id, name, 2 from t2
) t
group by id
over 4 years ago · Santiago Trujillo Report

0

from t1
union
select id, name
from t2 
over 4 years ago · Santiago Trujillo Report

0

select id, name
from t1
union all
select id, name
from t2
where not exists (select 1 from t1 where t1.id = t2.id)
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!