I have two tables with similar columns. I would simply like to select both tables, one after another, so that if I have 'x' rows on table1 and 'y' rows on table2, I'd get 'x + y' rows.
+6
A:
You would use UNION [ALL]
for this. The tables don't need to have the same column names but you do need to select the same number of columns from each and the corresponding columns need to be of compatible datatypes
SELECT col1,col2,col3 FROM table1
UNION ALL
SELECT col1,col2,col3 FROM table2
UNION ALL
is preferrable to UNION
where there is a choice as it can avoid a sort operation to get rid of duplicates.
Martin Smith
2010-08-17 16:17:34
his tables were clearly name table1 and table2, while x and y were used as row counts. i find this answer unacceptable... ;)
nathan gonzalez
2010-08-17 16:19:40
@nathan - I'll remedy this just to please you! Edit: Done.
Martin Smith
2010-08-17 16:21:02
i am overjoyed. +1
nathan gonzalez
2010-08-17 16:24:56
+2
A:
select col1,col2,col3 from table1
union
select col1,col2,col3 from table2
nathan gonzalez
2010-08-17 16:18:28
The OP wants all rows, therefore `UNION ALL`. A `UNION` will eliminate duplicates
Raj More
2010-08-17 16:19:36
+4
A:
Just to add to what they were saying, you might want to add an Order By. Depends on the version of SQL you're using.
SELECT Col1, Col2, Col3
FROM Table1
UNION
SELECT Col1, Col2, Col3
FROM Table2
ORDER BY Col1
Note that ORDER and GROUP BYs have to go after the last table in the UNION.
XstreamINsanity
2010-08-17 16:21:08