I would like to insert a few data into a table selecting data from a subquery having multiple joins.

I tried the following way:

insert into mytable (columns) 
select * from 
 (select columns 
  from tableA 
  UNION ALL 
  select columns from tableB 
  UNION ALL 
  select columns from tableC)

Can you please suggest me a way out, since I am getting the following error while executing the above query.

Incorrect syntax near ')'.

closed as off-topic by sp_BlitzErik, Md Haidar Ali Khan, mustaccio, MDCCL, Mr.Brownstone Oct 19 at 23:11

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Too localized - this could be because your code has a typo, basic error, or is not relevant to most of our audience. Consider revising your question so that it appeals to a broader audience. As it stands, the question is unlikely to help other users (regarding typo questions, see this meta question for background)." – sp_BlitzErik, Md Haidar Ali Khan, mustaccio, MDCCL, Mr.Brownstone
If this question can be reworded to fit the rules in the help center, please edit the question.

  • 1
    give the alias to your subquery, i.e. ")t" instead of ")" at the end of youe query – sepupic Oct 19 at 7:24
  • 1
    @sepupic, thanks for the help. It really worked – l.lijith Oct 19 at 7:44
up vote 3 down vote accepted

Add some alias:

insert into mytable (columns) 
select t.* from (
    select columns from tableA 
    UNION ALL
    select columns from tableB
    UNION ALL
    select columns from tableC
) t

Simply remove select * from ( and trailing ) from your query - it is excessive.

insert into mytable (columns) 
select columns from tableA 
UNION ALL 
select columns from tableB 
UNION ALL 
select columns from tableC

fiddle

Not the answer you're looking for? Browse other questions tagged or ask your own question.