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

Posted on 2008-11-07
Medium Priority
Last Modified: 2012-05-05

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

Question by:trumpman
LVL 93

Accepted Solution

Patrick Matthews earned 1200 total points
ID: 22907343
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
LVL 52

Assisted Solution

by:Mark Wills
Mark Wills earned 800 total points
ID: 22911748
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...


Featured Post

[Webinar] Improve your customer journey

A positive customer journey is important in attracting and retaining business. To improve this experience, you can use Google Maps APIs to increase checkout conversions, boost user engagement, and optimize order fulfillment. Learn how in this webinar presented by Dito.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In part one, we reviewed the prerequisites required for installing SQL Server vNext. In this part we will explore how to install Microsoft's SQL Server on Ubuntu 16.04.
It is possible to export the data of a SQL Table in SSMS and generate INSERT statements. It's neatly tucked away in the generate scripts option of a database.
Viewers will learn how to use the INSERT statement to insert data into their tables. It will also introduce the NULL statement, to show them what happens when no value is giving for any given column.
Viewers will learn how to use the UPDATE and DELETE statements to change or remove existing data from their tables. Make a table: Update a specific column given a specific row using the UPDATE statement: Remove a set of values using the DELETE s…

607 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question