Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using insert into ... select results in a incorrect syntax near select, why?

Tags:

sql

How can I make a SELECT inside an INSERT operation?

insert into tableX (a_id, b_id)  VALUES ((SELECT service_id           FROM tableY           WHERE id = 10, 2)); 

But the server returns a syntax error, why?

SQL Error [156] [S0001]: Incorrect syntax near the keyword 'select'. 
like image 472
aocferreira Avatar asked Jun 06 '11 16:06

aocferreira


People also ask

What does Incorrect syntax near mean in SQL?

When executing a query in SQL and the editor throws back this error: Incorrect syntax near …'' That typically means you have used the wrong syntax for the query. This happens mostly when someone switched from one relational database to another relational database, from MySQL to MS SQL Server for example.

Can insert be used with select?

You can use a select-statement within an INSERT statement to insert zero, one, or more rows into a table from the result table of the select-statement. The select-statement embedded in the INSERT statement is no different from the select-statement you use to retrieve data.

What does insert into select statement do?

The INSERT INTO SELECT statement copies data from one table and inserts it into another table. The INSERT INTO SELECT statement requires that the data types in source and target tables match. Note: The existing records in the target table are unaffected.

Why is insert into slower than select into?

Because the 'INSERT … SELECT' inserts data into an existing table, it is slower and requires more resources due to the higher number of logical reads and greater transaction log usage.


1 Answers

While my original answer gave a working solution, I was actually wrong about the cause of the error. There is nothing wrong with using a scalar subquery inside a VALUES clause. The problem with the statement in the question is simply that one parenthesis is in the wrong place; the scalar subquery must be enclosed in parentheses.

This should work:

insert into tableX (a_id, b_id)  VALUES (   (SELECT service_id           FROM tableY           WHERE id = 10)   , 2   ); 

Original Answer

VALUES can only be used in conjunction with literal values. However, literal values can be used in a subquery. Do this:

insert into tableX (a_id, b_id) SELECT service_id, 2 FROM tableY WHERE id = 10 
like image 104
Dave Costa Avatar answered Sep 28 '22 02:09

Dave Costa