Pages

Showing posts with label insert. Show all posts
Showing posts with label insert. Show all posts

Sunday, 25 August 2013

INSERT … SELECT

INSERT [LOW_PRIORITY | HIGH_PRIORITY] [IGNORE]
       [INTO] tbl_name [(col_name,...)]
       SELECT ...
       [ ON DUPLICATE KEY UPDATE col_name=expr, ... ]
With INSERT ... SELECT, you can insert many rows into a table from one or many tables. This is a method to insert data very fast.

Example:
INSERT INTO employee (dept_id,emp_name)
       SELECT d.d_id as dept_id, p.name as emp_name
       FROM department as d 
       JOIN people as p 
       ON d.category_id = p.category_id
       WHERE p.category_id < 20;

In the above example we have fetched the department ids and the names from the select query and inserted into the employee table.

Saturday, 24 August 2013

INSERT

The INSERT ... VALUES and INSERT ... SET forms of the statements are used to insert rows which have values that are explicitly specified.

INSERT [IGNORE]
       [INTO] tbl_name [(col_name,...)]
       {VALUES | VALUE} ({expr | DEFAULT},...),(...),...
       [ ON DUPLICATE KEY UPDATE col_name=expr
       [, col_name=expr] ... ]

OR
INSERT [IGNORE]
       [INTO] tbl_name
       SET col_name={expr | DEFAULT}, ...
       [ ON DUPLICATE KEY UPDATE col_name=expr
       [, col_name=expr] ... ]

The INSERT ...SELECT form inserts rows selected from another table or tables.

INSERT [IGNORE]    
       [INTO] tbl_name [(col_name,...)]
       SELECT ...
       [ ON DUPLICATE KEY UPDATE  col_name=expr
       [, col_name=expr] ... ]

You can use REPLACE instead of INSERT to overwrite old rows.
The following statement
will create a row with the fields with its default values:
INSERT INTO tbl_name () VALUES();

If you want to insert a value[dependent on the previous
column] into a  column, then you can use
expressions.
INSERT INTO tbl_name (col1,col2) VALUES(20,col1*5); 
This will create a row with a value 20 in col1 and 100 (i.e. 20*5) in col2. 
NOTE: You cannot use the columns in the expressions before they have been assigned values.
SO THE FOLLOWING STATEMENT BECOMES ILLEAGAL:
INSERT INTO tbl_name (col1,col2) VALUES(col2*5,20);