I have a database with two tables (Table1
and Table2
). They both have a common column [ColumnA]
which is an nvarchar
.
How can I select this column from both tables and return it as a single column in my result set?
So I'm looking for something like:
ColumnA in Table1:
a
b
c
ColumnA in Table2:
d
e
f
Result set should be:
a
b
c
d
e
f
In this approach you can join the two tables on the primary key of the two tables and use case statement to check whether particular column is matching between two tables. Select case when A. col1 = B. col1 then 'Match' else 'Mismatch' end as col1_cmpr, case when A.
In SQL we can retrieve data from multiple tables also by using SELECT with multiple tables which actually results in CROSS JOIN of all the tables.
The SQL intersect operator allows us to get common values between two tables or views. The following graphic shows what the intersect does. The set theory clearly explains what an intersect does. In mathematics, the intersection of A and B (A ∩ B) is the set that contains all elements of A that also belong to B.
To select multiple columns from a table, simply separate the column names with commas! For example, this query selects two columns, name and birthdate , from the people table: SELECT name, birthdate FROM people; Sometimes, you may want to select all columns from a table.
SELECT ColumnA FROM Table1 UNION Select ColumnB FROM Table2 ORDER BY 1
Also, if you know the contents of Table1 and Table2 will NEVER overlap, you can use UNION ALL in place of UNION instead. Saves a little bit of resources that way.
-- Kevin Fairchild
Do you care if you get dups or not?
UNION will be slower than UNION ALL because UNION will filter out dups
Use the UNION operator:
SELECT ColumnA FROM Table1
UNION
SELECT ColumnA FROM Table2
The union answer is almost correct, depending on overlapping values:
SELECT distinct ColumnA FROM Table1
UNION
SELECT distinct ColumnA FROM Table2
If 'd' appeared in Table1 or 'c' appeared in Table2 you would have multiple rows with them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With