Home > database >  How to Join two SELECT queries having same column names but different row values in both tables
How to Join two SELECT queries having same column names but different row values in both tables

Time:12-01

I got a table from SELECT Query 1 as below from SQL SERVER:

NUMBER NAME Date
21 Name1 20.03.2004
25 Name2 26.06.2005
23 Name3 26.06.2005
24 Name4 22.04.2012

I got a table from SELECT query 2 as below from SQL SERVER:

NUMBER NAME Date
30 Name10 20.03.2064
30 Name10 26.06.2035
35 Name30 26.06.2025
36 Name40 22.04.2042

I want to join these SELECT queries into one SELECT query like below

NUMBER NAME Date
21 Name1 20.03.2004
25 Name2 26.06.2005
23 Name3 26.06.2005
24 Name4 22.04.2012
30 Name10 20.03.2064
30 Name10 26.06.2035
35 Name30 26.06.2025
36 Name40 22.04.2042

I tried like this

Select * from ( select Number,Name,Date from table1 ) t1 
inner join ( select Number, Name, Date from table2) t2
on t1.number = t2.number

But it didnt work, This is not a actual table i want to join.

Basically I want to join two SELECT Query who got same Column names but have no common values between them. And I want to use SELECT query from the joined table.

Thank you

CodePudding user response:

    SELECT Number, Name, Date FROM table1
    UNION ALL
    SELECT Number, Name, Date FROM table2

CodePudding user response:

UNION and UNION ALL are SQL operators used to concatenate 2 or more result sets. This allows us to write multiple SELECT statements, retrieve the desired results, then combine them together into a final, unified set.

The main difference between UNION and UNION ALL is that:

UNION: only keeps unique records
UNION ALL: keeps all records, including duplicates

UNION Example:

SELECT column1 AS datacheck from table1 
  UNION 
SELECT column1 AS datacheck from table2

Result:

 ----------- 
| datacheck |
 ----------- 
|   data2   |
 ----------- 

UNION ALL example:

SELECT column1 AS datacheck from table1 
  UNION ALL
SELECT column1 AS datacheck from table2

Result:

 ----------- 
| datacheck |
 ----------- 
|   data2   |
|   data2   |
 ----------- 
  • Related