- Trending Categories
- Data Structure
- Operating System
- MS Excel
- C Programming
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to 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
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 −
As you can see, the values of perc_marks from the marks table have been successfully added to student_info.
- Related Articles
- MySQL query for INSERT INTO using values from another table?
- MySQL statement to copy data from one table and insert into another table
- How do I INSERT INTO from one MySQL table into another table and set the value of one column?
- Insert data from one table to another in MySQL?
- Copy column values from one table into another matching IDs in MySQL
- How to SELECT fields from one table and INSERT to another in MySQL?
- Insert from one table with different structure to another in MySQL?
- Insert values in a table by MySQL SELECT from another table in MySQL?
- MySQL trigger to insert row into another table?
- How do I insert all elements from one list into another in Java?
- How do I insert a record from one Mongo database into another?
- Take all records from one MySQL table and insert it to another?
- Fetch maximum ID value from the first table and insert to all the IDs in another table with MySQL INSERT INTO select?
- MySQL INSERT INTO SELECT resulting in multiple rows inserted at once from another table
- Insert data from one schema to another in MySQL?