148

I have two tables in SQL Server:

  1. article
  2. prices

Now I want to select a certain set of ids and insert some entries into the prices-table with those ID.

e.g. (wrong and not working SQL)

INSERT INTO prices (group, id, price) 
VALUES (7, (select articleId from article WHERE name LIKE 'ABC%'), 1.50);

SQL Error -> subquery has more than 1 value

1
  • 16
    Wow! So many correct answers all on Mar 13 '12 at 21:18 (hint: you can hover over the timestamp to get the seconds) Commented Dec 7, 2017 at 21:53

7 Answers 7

228

You want:

insert into prices (group, id, price)
select 
    7, articleId, 1.50
from article where name like 'ABC%';

where you just hardcode the constant fields.

Sign up to request clarification or add additional context in comments.

1 Comment

INSERT INTO iden_course (Cse_M_ID,Cse_M_Name,Cse_M_ShName, Cse_M_TotSem,Cse_M_CreatedDate) VALUES ('ID','BJf', 'BJfg' , '4',Now()) select max(Cse_M_ID) as ID from iden_course how to add in this query
34

Try this:

INSERT INTO prices (
    group, 
    id,
    price
) 
SELECT
    7,
    articleId,
    1.50
FROM
    article 
WHERE 
    name LIKE 'ABC%';

Comments

18

If you are inserting one record into your table, you can do

INSERT INTO yourTable 
VALUES(value1, value2)

But since you want to insert more than one record, you can use a SELECT FROM in your SQL statement.

so you will want to do this:

INSERT INTO prices (group, id, price) 
SELECT 7, articleId, 1.50
from article 
WHERE name LIKE 'ABC%'

Comments

14
INSERT INTO prices (group, id, price)
  SELECT 7, articleId, 1.50 FROM article WHERE name LIKE 'ABC%'

Comments

6

i am using this method.

WITH selected AS (
   SELECT articleId FROM article WHERE name LIKE 'ABC%'
) INSERT INTO prices(group, id, price)
  SELECT 7, articleId, 1.50 from selected;

1 Comment

From a performance perspective, this method is much preferred and yielded me a gain of x27 on PostgreSQL 12, relative to the accepted answer.
5

the sub query looks like

 insert into table_name (col1,col2,....) values (select col1,col2,... FROM table_2 ...)

hope this help

Comments

1
INSERT INTO prices(group, id, price)
SELECT 7, articleId, 1.50
FROM article where name like 'ABC%';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.