0

As I read here If I want to insert into a table from another in PostgreSQL database I have to use this:

This query inserts some rows from another table

INSERT INTO books (id, title, author_id, subject_id)
       SELECT nextval('book_ids'), title, author_id, subject_id
              FROM book_queue WHERE approved;

But how can I insert a row with more columns with my custom data(default or non default)?

E.g., books (id, title, author_id, <a cell with my data1>,subject_id,<a cell with my data2>)

And how can I update a selected data before inserting into a table?

I.e., something like:

INSERT INTO books (id, title, author_id, subject_id)
       SELECT nextval('book_ids'), title, author_id+1, subject_id/2
              FROM book_queue WHERE approved;
2
  • What exactly is <a cell with my dataX>? Is that a row from some other table? Some other well-defined data? The way you phrase your question you will not get a proper answer; please provide more details. Commented Sep 13, 2015 at 7:52
  • This is some integer value or string value Commented Sep 13, 2015 at 9:31

1 Answer 1

1

Insert inserts rows, and select generates/forms rows, so if you can build the data you want to insert with any select statement, then you can insert it, even if there are new fields or updated fields. For example:

INSERT INTO books (title, author_id, subject_id, combined)
  SELECT title, author_id+1, subject_id/2, author_id || ' ' || title
    FROM book_queue WHERE approved;

Here is a fiddle to play with.

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

1 Comment

Thanks. That's what I want. This is very difficult to find good examples. Congratulate with 1k scores:)

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.