Skip to content

SQL, copy data from one table to another

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.

I wrote 17 books to help you become a better developer, download them all at $0 cost by joining my newsletter

  • C Handbook
  • Command Line Handbook
  • CSS Handbook
  • Express Handbook
  • Git Cheat Sheet
  • Go Handbook
  • HTML Handbook
  • JS Handbook
  • Laravel Handbook
  • Next.js Handbook
  • Node.js Handbook
  • PHP Handbook
  • Python Handbook
  • React Handbook
  • SQL Handbook
  • Svelte Handbook
  • Swift Handbook

JOIN MY CODING BOOTCAMP, an amazing cohort course that will be a huge step up in your coding career - covering React, Next.js - next edition February 2025

Bootcamp 2025

Join the waiting list