Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nested SELECT in INSERT sql statement [closed]

Can someone tell me why this doesnt work?

INSERT INTO Medical_History (pid, grafts, allergies,  diseases, surgearies, treatment)
VALUES ((SELECT pid FROM Pet WHERE pet_name='Jack' AND cid=(SELECT cid FROM Customer WHERE last_name='Iwannidis' AND first_name='Giwrgos')),
       'grafts', 'allergies', 'diseases', 'surgearies', treatments');

I get a syntax error:

unrecognized token "');"
like image 762
lephleg Avatar asked May 28 '13 01:05

lephleg


People also ask

Can you use a subquery in an insert statement?

Subqueries also can be used with INSERT statements. The INSERT statement uses the data returned from the subquery to insert into another table. The selected data in the subquery can be modified with any of the character, date or number functions.

Can subqueries be used in inserts deletes and/or updates?

Subqueries can be used with SELECT, UPDATE, INSERT, DELETE statements along with expression operator.


2 Answers

The select nested in the values statement looks wrong (and I'm not sure that all databases accept it). A more typical way to express this is:

INSERT INTO Medical_History (pid, grafts, allergies,  diseases, surgearies, treatment)
    SELECT pid, 'grafts', 'allergies', 'diseases', 'surgearies', 'treatments'
    FROM Pet
    WHERE pet_name='Jack' AND
          cid=(SELECT cid
               FROM Customer
               WHERE last_name='Iwannidis' AND first_name='Giwrgos'
              );

This is particularly important if the subquery returns more than one value. Then the query is likely to get an error.

like image 181
Gordon Linoff Avatar answered Sep 26 '22 07:09

Gordon Linoff


I had a syntax error because I had forgotten the quotes (') on 'treatments'.

like image 26
lephleg Avatar answered Sep 26 '22 07:09

lephleg