AKIWEB
AKIWEB

Reputation: 19612

How to insert same data (or copy) in a same table for different record in postgres

I have a table called Records which have data as following-

Section_one | section_two | values       | cDate

name_Fit    | hellp0      | present      | 2014-08-23
name_Fit    | onew        | parcel       | 2014-08-21
name_Fit    | twow        | new thing    | 2014-07-04

Now I am trying to insert a new data called name_Fit_one w.r.t to column section_one which should have similar data (w.r.t column section_two and values) corresponding to it.

I tried to write the sql to do that but I am getting error on postgres. Can anyone please correct me what am I doing wrong?

Insert into records(section_one,section_two,values) Values ('name_Fit_one', select section_two,values from records where section_one='name_Fit');

Expected Results

Section_one | section_two | values       | cDate

name_Fit    | hellp0      | present      | 2014-08-23
name_Fit    | onew        | parcel       | 2014-08-21
name_Fit    | twow        | new thing    | 2014-07-04
name_Fit_one| hellp0      | present      | 2014-08-29
name_Fit_one| onew        | parcel       | 2014-08-29
name_Fit_one| twow        | new thing    | 2014-08-29

Need to write single query that would copy content of one record to another record?

Below is the sql fiddle for it-

http://sqlfiddle.com/#!2/9de58/1

Upvotes: 0

Views: 5324

Answers (2)

Brian DeMilia
Brian DeMilia

Reputation: 13248

If you're using postgresql you should be able to use:

Insert into records
  select 'name_Fit_one', section_two, values, '2014-08-29'
    from records
   where section_one = 'name_Fit';

Fiddle: http://sqlfiddle.com/#!15/fbbed/1/0

Note that I renamed some of your columns as it was unclear whether your example above or your sqlfiddle contained your actual data and column names (they differ).

You can replace the literal '2014-08-29' with CURRENT_DATE if you want it to be the date in which you run the insert.

Upvotes: 3

user330315
user330315

Reputation:

Insert into records (section_one,section_two, "values") 
select 'name_Fit_one', section_two, "values" 
from records 
where section_one='name_Fit';

Note that values is a reserved word and thus needs to be quoted.

Upvotes: 1

Related Questions