How can I correct my SQL syntax to allow for a subquery?


I need help adding with my SQL syntax.  The problem centers around a query within a query.
INSERT INTO table1(val1, val2, val3) select val1,(SELECT TOP 1 * from table2 ORDER BY val1 DESC) + 1, 1 from table3'

Open in new window

Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Patrick MatthewsCommented:
Looks like you want the minimum from a column...

INSERT INTO table1 (val1, val2, val3)
SELECT val1,
    (SELECT MIN(t2.val1) FROM table2 t2) + 1,
FROM table3

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Mark WillsTopic AdvisorCommented:
you cannot select multiple columns in the subquery, so, need to understand what you are trying to retrieve from table2

assuming it is val1 from table2, then matthewspatrick suggestion is a good one.  using your original syntax, just swap the * for the name of the column. which works well when there is a different column to order by from the value you are trying to return (e.g. like a date being "most recent" or something), otherwise use the aggregate functions as suggested by matthewspatrick - but should have been MAX...

e.g.1 original syntax:

INSERT INTO table1(val1, val2, val3) select val1,(SELECT TOP 1 val1 from table2 ORDER BY val1 DESC) + 1, 1 from table3

e.g.2 matthews updated syntax:

INSERT INTO table1 (val1, val2, val3)  SELECT val1,  (SELECT MAX(val1) FROM table2) + 1, 1 FROM table3

and might also be worthwhile checking for NULL just for completeness...

It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft SQL Server 2008

From novice to tech pro — start learning today.