Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL: Select like column from two tables

Tags:

sql

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
like image 803
Jared Avatar asked Sep 04 '08 17:09

Jared


People also ask

How can we find similar columns in two tables in SQL?

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.

Can you SELECT columns from multiple tables in SQL?

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.

How do you SELECT common values from two tables in SQL?

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.

How do I SELECT multiple columns from multiple tables in SQL?

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.


4 Answers

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

like image 112
Kevin Fairchild Avatar answered Nov 13 '22 07:11

Kevin Fairchild


Do you care if you get dups or not?

UNION will be slower than UNION ALL because UNION will filter out dups

like image 44
SQLMenace Avatar answered Nov 13 '22 08:11

SQLMenace


Use the UNION operator:

SELECT ColumnA FROM Table1
UNION
SELECT ColumnA FROM Table2
like image 33
Joseph Sturtevant Avatar answered Nov 13 '22 07:11

Joseph Sturtevant


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.

like image 24
Unsliced Avatar answered Nov 13 '22 07:11

Unsliced