tags:

views:

3799

answers:

8

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
+10  A: 
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

Kevin Fairchild
You can do ORDER BY 1 in your first query to avoid the need for the subquery when ordering.
Good catch. Thanks.
Kevin Fairchild
+1  A: 

Use the UNION operator:

SELECT ColumnA FROM Table1
UNION
SELECT ColumnA FROM Table2
Joseph Sturtevant
A: 

You can use a union select:

Select columnA from table1 union select columnA from table2
Haydar
A: 
SELECT Table1.*, Table2.d, Table2.e, Table2.f 
FROM Table1 JOIN Table2 ON Table1.a = Table2.a

Or am I misunderstanding your question?

Edit: It appears I did.

JesDaw
My initial read of the question was the same as yours, JesDaw. Original poster, it would have been a little clearer to explain that "a, b, c", etc, were the *values* in ColumnA, especially since you used the letter a for both a column and a value. Just nitpicking, I guess.
Ian Varley
A: 

I believe it's:

SELECT columna FROM table1 UNION SELECT columnb FROM table2;
Nathan Fritz
+2  A: 

Do you care if you get dups or not?

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

SQLMenace
A: 

In Oracle (at least) there is UNION and UNION ALL, UNION ALL will return all results from both sets even if there are duplicates, where as UNION will return the distinct results from both sets.

Ethan Post
+1  A: 

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.

Unsliced