Insert Values from One Table into Another in PostgreSQL



Suppose you have two tables: marks and student_info. Examples are given below for the two respectively

name roll_no perc_marks
Aniket 12 24
Siddhi 45 65
Yash 26 42
Isha 56 87


name roll_no age gender
Aniket 12 26 M
Isha 56 25 F
Siddhi 45 23 F
Yash 26 25 M

Now, suppose your manager at work looks at the two tables and tells you, “Why do we have two tables? Simplify things, shift everything to one table!”

So you decide to add the perc_marks column to the student_info table.

ALTER TABLE student_info
ADD COLUMN perc_marks integer

Now, how will you populate this column? Will you manually add the marks for each column? That will leave the room open for a lot of errors and will also be very time-consuming. Instead, this is what you could do −

UPDATE student_info
SET perc_marks = marks.perc_marks FROM marks
WHERE student_info.roll_no = marks.roll_no

Here, the roll_no is used as the common field between the two tables and update values for marks in the student_info table. Please note that the assumption here is that there is only one entry for each roll_no in the marks table. If there are multiple rows having the same roll_no in the marks table, it will confuse PostgreSQL. Generally, a primary key/ foreign key is used as the common field, to avoid this confusion.

Now, if you query the student_info table (SELECT * from student_info), you will see the following output −

name roll_no age gender perc_marks
Aniket 12 26 M 24
Isha 56 25 F 87
Siddhi 45 23 F 65
Yash 26 25 M 42

As you can see, the values of perc_marks from the marks table have been successfully added to student_info.

Updated on: 2021-02-02T12:30:41+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements