In MySQL, the INSERT
Query allows you to enter data into your table of choice.
However, there could be times when you want to insert the same data into table A
that you have inserted into another table B
, even though they are not of the same database.
The need for such actions may occur when:
So, how can we achieve this particular function?
INSERT INTO //name of new table and columns to be fi
SELECT // columns of the existing table to be copied from
FROM //name of existing table
Let’s say we have a students
table in a school
database. We notice that this table is a bit congested and needs to be cleaned up by creating more separation.
One of the tables we created is the grade_report
table. This grade_report
table, as shown in the below code, has the subjects
, grades
, score
, and student_id
columns, which will be filled with the existing data in the students table
.
Below is our sample students
table.
id | Fname | Lname | class | accum_grade | student_grade |
1 | Tina | Llee | 2 | 70 | A |
2 | Mark | Obi | 3 | 60 | B |
3 | Michel | Larry | 6 | 50 | C |
4 | Tom | Constantine | 4 | 40 | F |
INSERT INTO grade_report (subjects, grades, score, student_id)SELECT courses, student_grade, accum_score,idFROM students ORDER BY id DESC
In the example above, columns of our student
table that are ordered by the student ID in a descending order are selected, from which we will make the grade_report
table.