2

I want to insert records into the "books" table for every author in the "author" table. In other words, if this represented the author table:

> 1 - "Herman Melville" 
> 2 - "Stephen King" 
> 3 - "Truman Capote"

...then, the insert would yield these results in the "book" table:

> 'Hello World' - 1
> 'Hello World' - 2
> 'Hello World' - 3

I have the following INSERT statement (it's actually a crude example, but it demonstrates the objective):

INSERT INTO books (title, author_id) VALUES ('Hello World', SELECT id FROM author);

Unfortunately, this fails and I'm uncertain how to get each of the "id" values from the "author" table.

4 Answers 4

9

It's not clear why you'd want to insert the same entry for each author, but you could use a SELECT as the source for your INSERT, like this:

INSERT INTO books (title, author_id)
    SELECT 'Hello World', id
    FROM author

Edit: for some more info, check the docs for INSERT; as you can see, the source can be either DEFAULT VALUES, VALUES or a query.

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

Comments

3

You can use this one:

INSERT INTO books (title, author_id) SELECT 'Hello World', id FROM author;

Comments

2

You can also surround your subselect with parentheses:

 INSERT INTO books (title, author_id) 
  VALUES ('Hello World',  (SELECT id FROM author WHERE...) );

This syntax might be easiest to understand, but the other syntax pointed by other commenters (without VALUES) is probably more clean : you just build out the fly the record you want to insert (with a SELECT) and then you INSERT it; it could also be more efficient if you had many subselects for distict fields.

Comments

1
INSERT INTO books (title, author_id) SELECT 'Hello World', id FROM author

4 Comments

Exact dupe of the one above it. Please consider removing the answer.
@Huuuze To be fair, the "one above" was posted afterwards, some 18 minutes afterwards. Let the community decide which one they like.
@Lasse Um, nope. After the down vote, it's two up -- they're posted at the exact same time. Look more closely next time.
Yeah, I missed which one you were talking about, the ordering here is random when things have the same amount of votes, so "above" and "below" is easy to get wrong. I see what you mean now. Sorry.

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.