Combining several query results into one table, how is the results order determined? - sql

I am retuning table results for different queries but each table will be in the same format and will all be in one final table. If I want the results for query 1 to be listed first and query2 second etc, what is the easiest way to do it?
Does UNION append the table or are is the combination random?

The SQL standard does not guarantee an order unless explicitly called for in an order by clause. In practice, this usually comes back chronologically, but I would not rely on it if the order is important.
Across a union you can control the order like this...
select
this,
that
from
(
select
this,
that
from
table1
union
select
this,
that
from
table2
)
order by
that,
this;

UNION appends the second query to the first query, so you have all the first rows first.

You can use:
SELECT Col1, Col2,...
FROM (
SELECT Col1, Col2,..., 1 AS intUnionOrder
FROM ...
) AS T1
UNION ALL (
SELECT Col1, Col2,..., 2 AS intUnionOrder
FROM ...
) AS T2
ORDER BY intUnionOrder, ...

Related

Using distinct on in subqueries

I noticed that in PostgreSQL the following two queries output different results:
select a.*
from (
select distinct on (t1.col1)
t1.*
from t1
order by t1.col1, t1.col2
) a
where a.col3 = value
;
create table temp as
select distinct on (t1.col1)
t1.*
from t1
order by t1.col1, t1.col2
;
select temp.*
from temp
where temp.col3 = value
;
I guess it has something to do with using distinct on in subqueries.
What is the correct way to use distinct on in subqueries? E.g. can I use it if I don't use where statement?
Or in queries like
(
select distinct on (a.col1)
a.*
from a
)
union
(
select distinct on (b.col1)
b.*
from b
)
In normal situation, both examples should return the same result.
I suspect that you are getting different results because the order by clause of your distinct on subquery is not deterministic. That is, there may be several rows in t1 sharing the same col1 and col2.
If the columns in the order by do not uniquely identify each row, then the database has to make its own decision about which row will be retained in the resultset: as a consequence, the results are not stable, meaning that consecutive executions of the same query may yield different results.
Make sure that your order by clause is deterministic (for example by adding more columns in the clause), and this problem should not arise anymore.

Union of multiple queries using the count function

I'm working on learning more about how the UNION function works in SQL Server.
I've got a query that is directed at a single table:
SELECT Category, COUNT(*) AS Number
FROM Table1
GROUP BY Category;
This returns the number of entries for each distinct line in the Category column.
I have multiple tables that are organized by this Category column and I'd like to be able to have the results for every table returned by one query.
It seems like UNION will accomplish what I want it to do but the way I've tried implementing the query doesn't work with COUNT(*).
SELECT *
FROM (SELECT Table1.Category
Table1.COUNT(*) AS Number
FROM dbo.Table1
UNION
SELECT Table2.Category
Table2.COUNT(*) AS Number
FROM dbo.Table2) AS a
GROUP BY a.Category
I'm sure there's an obvious reason why this doesn't work but can anyone point out what that is and how I could accomplish what I'm trying to do?
You cannot write a common Group by clause for two different select's. You need to use Group by clause for each select
SELECT TABLE1.Category, --missing comma here
COUNT(*) as Number -- Remove TABLE1. alias name
FROM dbo.TABLE1
GROUP BY Category
UNION ALL --UNION
SELECT TABLE2.Category, --missing comma here
COUNT(*) as Number -- Remove TABLE1. alias name
FROM dbo.TABLE2
GROUP BY Category
If you really want to remove duplicates in result then change UNION ALL to UNION
COUNT as any associated aggregation function has to have GROUP BY specified. You have to use group by for each sub query separately:
SELECT * FROM (
SELECT TABLE1.Category,
COUNT(*) as Number
FROM dbo.TABLE1
GROUP BY TABLE1.Category
UNION ALL
SELECT TABLE2.Category,
COUNT(*) as Number
FROM dbo.TABLE2
GROUP BY TABLE2.Category
) as a
It is better to use UNION ALL vs UNION - UNION eliminates duplicates from result sets, since - let say - you want to merge both results as they are it is safer to use UNION ALL

I need help combining a few select statements

I would like to pull all of the columns from my second select statement and put it to the right of all of my columns from my first statement.
I have tried Union and the join commands with no luck.
When I use these they just have what I wanted from my first select statement.
Here is basic code I have.
Select * from MTG_TREND where LINEID='A2' end;
Select * from MTG_TREND where LINEID='B2'
All of the other columns are the same.
Select t1.*,t2.* from MTG_TREND t1
left join (
Select * from MTG_TREND where LINEID='B2'
) as t2
on t1.primarykey=t2.primarykey
where t1.LINEID='A2'
NOTE:
- Make sure you are matching the same number of columns in both SELECT Statement.
- Another thing to remember is you have to have the same matched column (datatype).
- If there are some columns that are not present is the table then just defined the column with null so that you can get it in output from another select statement.
Select col1, col2, col3,...... from MTG_TREND where LINEID='A2'
UNION ALL
Select col1, col2, col3,...... from MTG_TREND where LINEID='B2'

Sql Merging two result sets

Lets take two result sets as in: 1,2,3,5,7 and 2,4,6,7,8
In the end I want 1,2,3,4,5,6,7,8. I can not figure out how to code this in sql. Can any one give me some suggestions? I've seen some merging functions out there but having trouble implementing something simple.
You may use UNION
(SELECT id FROM table1 WHERE 1=1)
UNION
(SELECT id FROM table2 WHERE 1=1)
ORDER BY id
I think maybe you're thinking of UNION?
If SELECT `Column` FROM `Table` yields 1,2,3,5,7
And SELECT `Column` FROM `Table2` yields 2,4,6,7,8
Then
SELECT `Column` FROM `Table`
UNION
SELECT `Column` FROM `Table2`
yields 1,2,3,4,5,6,7,8

Override alphabetical default ORDER BY with a UNION of 2+ tables?

Really quick question... I have 4 tables that are UNION-ed together like so:
SELECT * FROM table1
UNION
SELECT * FROM table2
UNION
SELECT * FROM table3
UNION
SELECT * FROM table4
Without specifying an ORDER BY, the query orders by the first column in ascending alphabetical order (which in my case happens to be a varchar type). I don't want ORDER BY [Column1] DESC either.
I simply want to order the results in the same order as the tables themselves are UNION-ed. 1, 2, 3, 4.
Is there a simply way to do this?
Thanks!!
One way
SELECT *,1 as SortOrder FROM table1
UNION
SELECT *,2 FROM table2
UNION
SELECT *,3 FROM table3
UNION
SELECT *,4 FROM table4
order by SortOrder
what happens is that you are using UNION, sql server then makes the result set distinct, in order to do that it needs to sort the tables
Does UNION ALL make a difference?
We had a similar issue. We have a union query with 32 subsets. We use it to populate a spreadsheet that is then used to build a PowerPoint presentation. The first field in each query is a text field that is a description of the data point. The spreadsheet is expecting the data to be in a specific order.
We made a slight change to one of the fields:
Concat('Annual incidence rate- ', Year(start_date))
This caused SQL to sort the unions in alphabetical order! I suspect that if you ordered your query as #SQLMenace indicated, but with a slight modification, it would work too.
SELECT '1', * FROM table1
UNION
SELECT '2', * FROM table2
UNION
SELECT '3', * FROM table3
UNION
SELECT '4', * FROM table4
This might alleviate the outer query wrapper. It might work without the quotes, too.