HiveBrain v1.2.0
Get Started
← Back to all entries
debugMinor

INSERT INTO with UNION Alias ERROR

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
errorinsertwithintounionalias

Problem

This question is derived from the following post UNION query not working

Fails:

INSERT INTO AssetControl  
SELECT *  
FROM CSVImport  
UNION SELECT *  
FROM AssetTemp;


Works:

INSERT INTO AssetControl  
SELECT U.* FROM  
(SELECT * FROM CSVImport  
UNION  
SELECT * FROM AssetTemp) AS U


I don't understand why an alias U needs to be created in order for the records to be successfully input into the AssetControl table. Can anyone shed some light on this?

Solution

The short answer is: Access is weird ;)

Long answer is that Access has certain restrictions in the SQL syntax it supports. It requires parentheses around some constructions, for example when more than 2 tables are joined.

I think the same applies here. It's not that an alias is required, it's that (Access) syntax requires parentheses in INSERT INTO tableA SelectQueryB; when SelectQuery is a UNION query, even though the SQL standard does not require them. I think[1] that this works, too (and doesn't need an alias):

INSERT INTO AssetControl  
(SELECT * FROM CSVImport  
UNION  
SELECT * FROM AssetTemp) ;


[1]: It appears that this is not allowed either.

Your solution works because it's equivalent to the standard use of INSERT .. SELECT:

INSERT INTO AssetControl  
SELECT U.* 
FROM SomeTable AS U ;


where SomeTable is replaced by a derived table:

(SELECT * FROM CSVImport  
UNION  
SELECT * FROM AssetTemp)

Code Snippets

INSERT INTO AssetControl  
(SELECT * FROM CSVImport  
UNION  
SELECT * FROM AssetTemp) ;
INSERT INTO AssetControl  
SELECT U.* 
FROM SomeTable AS U ;
(SELECT * FROM CSVImport  
UNION  
SELECT * FROM AssetTemp)

Context

StackExchange Database Administrators Q#160877, answer score: 3

Revisions (0)

No revisions yet.