Tuesday, April 29, 2008

Copying tables in MySQL

The other day I was asked by friend on how a table could be copied in mysql, this query made me think that I should list down some interesting yet simple statements which might be important to people.

QUERY 1: If you want to create a new table out of an existing one

create table City2 like City;

This would create a new table with the same structure as City, but the rows in City will not be copied to City2.

QUERY 2: If you want to create a new table along from an existing table along with all the existing data.

create table City3 select * from City;

QUERY 3: If you want to select only a few columns and create a new table from an existing one

create table City4 select Name,CountryCode from City;

QUERY 4: If you want to copy all data from one table to the other

insert into City2 select * from City;

QUERY 5: If you want to copy certain data from one table to the other

insert into City6(Name, CountryCode) select Name, CountryCode from City;

** NOTE in this query we do not have a values part in the insert query.

No comments: