Postgresql version: 9.1.9
I'm trying to insert data into a table using SELECT and passing values
Example of what i try to accomplish:
current database:
MyTable
character number
'a' '0'
'b' '1'
'c' '1'
what i want:
MyTable
character number
'a' '0'
'b' '1'
'c' '1'
'b' '2'
'c' '2'
I tried different things but i can't seem to get it right. For example:
INSERT INTO MyTable (character, number)
(SELECT character FROM MyTable WHERE number = '1', '2')
Note: The numbers are actually long strings and therefore have to be in brackets.
Thanks.
You can use a select-statement within an INSERT statement to insert zero, one, or more rows into a table from the result table of the select-statement. The select-statement embedded in the INSERT statement is no different from the select-statement you use to retrieve data.
INSERT INTO SELECT vs SELECT INTO: Both the statements could be used to copy data from one table to another. But INSERT INTO SELECT could be used only if the target table exists whereas SELECT INTO statement could be used even if the target table doesn't exist as it creates the target table if it doesn't exist.
INSERT INTO MyTable (character, number)
SELECT character, '2' FROM MyTable WHERE number = '1'
to save the data in the same format on your example
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With