Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

mysql
databases
communitycreator

How to INSERT data from one Table into another in MySQL

NDUKWE CHIDERA K.

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:

  • You wish to create a new table in another Database which might have a column or more that holds the same data as the data in another table.
  • There is need for simplifying said tables into simple ones, maybe in the same database.

So, how can we achieve this particular function?

The SQL commands to use

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 

Example

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.

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,id  
FROM 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.

RELATED TAGS

mysql
databases
communitycreator
RELATED COURSES

View all Courses

Keep Exploring