How to insert values in table from another table

Points To Remember
  • We can use subqueries in databases like Mysql and avoid multiple queries.
  • Syntax - INSERT INTO table1 SELECT * FROM table2;
  • We do not write VALUES in the query. 
Example : Insert Values from one table to another.
Suppose we have two table person and person_old with columns
  • id int primary key
  • name varchar
  • age number
  • contact varchar
  • description text
And we want to copy all the details of the table person_old to table person. Then we must write our query as. This will insert all the rows of the person_old table to the new table person.
insert into person select * from person_old;

Also if we want to add only a few columns of the table person_old to the table person.Suppose we want to add only name, age and contact to the table person from table person_old where age is less than 25, then we can query as follows.
insert into person(name,age,contact) select name,age,contact from person_old  where age < 25;

No comments:

Powered by Blogger.