Skip to content

SQL, copy data from one table to another

New Course Coming Soon:

Get Really Good at Git

One of those maintenance tasks: copying data from one table to another.

You can copy all elements from a table into another like this:

INSERT INTO some_table 
SELECT * FROM other_table

Of course you can just select some if you want:

INSERT INTO some_table 
SELECT * FROM other_table WHERE list=94

If the table you’re copying to has existing data, you might have primary key duplication issues.

To leave the primary key column empty to make the table auto-fill it with its auto increment, I selected all columns except the primary key:

INSERT INTO some_table (`age`, `name`, `email`)
SELECT `age`, `name`, `email` FROM other_table

In my case id was the primary key column, and I left it out.

Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. A course that helps you feel less frustrated with Git. Launching Summer 2024. Join the waiting list!
→ Read my SQL Tutorial on The Valley of Code

Here is how can I help you: