Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgresql: INSERT INTO using SELECT and values

Tags:

sql

postgresql

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.

like image 533
Emiel Steerneman Avatar asked Nov 05 '13 22:11

Emiel Steerneman


People also ask

Can we use insert and select together?

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.

What is the difference between insert into and select into?

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.


1 Answers

INSERT INTO MyTable (character, number) 
    SELECT character, '2' FROM MyTable WHERE number = '1'

to save the data in the same format on your example

like image 125
pobrelkey Avatar answered Sep 20 '22 16:09

pobrelkey