UNION INTO

So, this appears to have worked:

SELECT *
INTO [COPD].[dbo].[COPDCombinedGlucoseResults]
FROM [COPD].[dbo].[COPDLabGlucoseResults]
UNION
SELECT *
FROM [COPD].[dbo].[COPDFlowsheetGlucoseResults];

The new table has 156558 rows

The LabGlucose table had 137417 distinct rows and the Flowsheet Glucose table had 72986 distinct rows, so I think that means there were 53845 matching rows.

Just for grins, and because this was my first real-live UNION query, I thought it would be interesting to do an INTERSECT query to see if the 53845 number holds water and to test my newbie understanding of these queries:

SELECT *
FROM [COPD].[dbo].[COPDLabGlucoseResults]
INTERSECT
SELECT *
FROM [COPD].[dbo].[COPDFlowsheetGlucoseResults];

Lo and Behold: 53845 rows. So if you add the results of a UNION query to the results of an INTERSECT query, you will get the same number of rows as both tables separately.

I read today about the UNION ALL query, and it appeared to be the version of the UNION query that included duplicate rows.

By this logic, a UNION query + an INTERSECT query = a UNION ALL query. I must test this.

The number of rows from each table add up to: 210403

SELECT *
FROM [COPD].[dbo].[COPDLabGlucoseResults]
UNIONĀ ALL
SELECT *
FROM [COPD].[dbo].[COPDFlowsheetGlucoseResults];

and we have a winner! 210403 rows.

I think I might possibly be falling in love with SQL. I’ve almost forgotten my garden.

Advertisements