INSERT INTO class
(name, description, personid)
Select name, description, 12 from Class where PersonID = 3;
Select * from Class
Select * from Person
Why is the values words is missing from above statement? I thought it should be like this insert into tableA('name') values('select name from tableB') ?
INSERT INTO my_table VALUES ()
Insert data one Table to another table
OR
Not Using Value keyword
Insert into Table2 (Name , Address , Mobile) Select Column 1, Column 2 , Column 3 From Table1
There are different techniques of INSERT, the code above is inserting values from the table itself and change only the personid to 12, he use select so that he can copy the data aside from hardcoded personid . that's why you didn't see the VALUES keyword , but that's true.. the basic insert statement we learn from school is INSERT INTO TableName (Col1, Col2... etc) VALUES (Value1, Value2... etc) , INSERTION of data depends on the requirements that you are working on.
Related
I have a query that inserts using a SELECT statement:
INSERT INTO courses (name, location, gid)
SELECT name, location, gid
FROM courses
WHERE cid = $cid
Is it possible to only select "name, location" for the insert, and set gid to something else in the query?
Yes, absolutely, but check your syntax.
INSERT INTO courses (name, location, gid)
SELECT name, location, 1
FROM courses
WHERE cid = 2
You can put a constant of the same type as gid in its place, not just 1, of course. And, I just made up the cid value.
Yes, it is. You can write :
INSERT INTO courses (name, location, gid)
SELECT name, location, 'whatever you want'
FROM courses
WHERE cid = $ci
or you can get values from another join of the select ...
Correct Syntax: select spelling was wrong
INSERT INTO courses (name, location, gid)
SELECT name, location, 'whatever you want'
FROM courses
WHERE cid = $ci
Sure, what do you want to use for the gid? a static value, PHP var, ...
A static value of 1234 could be like:
INSERT INTO courses (name, location, gid)
SELECT name, location, 1234
FROM courses
WHERE cid = $cid
Of course you can.
One thing should be noted however: The INSERT INTO SELECT statement copies data from one table and inserts it into another table AND requires that data types in source and target tables match. If data types from given table columns does not match (i.e. trying to insert VARCHAR into INT, or TINYINT intoINT) the MySQL server will throw an SQL Error (1366).
So be careful.
Here is the syntax of the command:
INSERT INTO table2 (column1, column2, column3)
SELECT column1, column2, column3 FROM table1
WHERE condition;
Side note: There is a way to circumvent different column types insertion problem by using casting in your SELECT, for example:
SELECT CAST('qwerty' AS CHAR CHARACTER SET utf8) COLLATE utf8_bin;
This conversion (CAST() is synonym of CONVERT() ) is very useful if your tables have different character sets on the same table column (which can potentially lead to data loss if not handled properly).
We all know this works.
INSERT INTO `TableName`(`col-1`,`col-2`)
SELECT `col-1`,`col-2`
===========================
Below method can be used in case of multiple "select" statements. Just for information.
INSERT INTO `TableName`(`col-1`,`col-2`)
select 1,2 union all
select 1,2 union all
select 1,2 ;
The right Syntax for your query is:
INSERT INTO courses (name, location, gid)
SELECT (name, location, gid)
FROM courses
WHERE cid = $cid
i want to insert the scholar's id to the tblinbox. Here is my query:
$sql = "INSERT INTO tblinbox VALUES ('','$sender','$type','$subject','$LRN','$content','$date', '$newyearLevel','','$userType','THIS_IS_FOR_THE_ID_OF_THE_SCHOLAR')
SELECT id FROM tblscholar WHERE schoYear = '$newyearLevel'";
my problem is,it is not inserting. what will i change in my query?
INSERT ... SELECT syntax does not allow for VALUES declaration. The values ARE the results returned from the SELECT.
See the documentation here: http://dev.mysql.com/doc/refman/5.6/en/insert-select.html
I honestly am not fully sure what you are trying to do with your insert. If you are trying to insert the same values held in your variables for each id value from the tblscholar table then perhaps you need to do something like this:
INSERT INTO tblinbox
/*
maybe add column definitions here to make it clearer
column definitions could look like this:
(
someField,
type,
subject,
LRN,
content,
`date`,
newyearLevel,
someOtherField,
userType,
id
)
*/
SELECT
'',
'$sender',
'$type',
'$subject',
'$LRN',
'$content',
'$date',
'$newyearLevel',
'',
'$userType',
id
FROM tblscholar
WHERE schoYear = '$newyearLevel'
An INSERT statement supports either a VALUES clause followed by a row of values, or else a SELECT query with columns to match the columns of the table you want to insert into.
But not both!
But you can add constant values into your SELECT query:
$sql = "INSERT INTO tblinbox
SELECT '','$sender','$type','$subject','$LRN','$content','$date',
'$newyearLevel','','$userType', id
FROM tblscholar WHERE schoYear = '$newyearLevel'";
considering id is the first column in your insert statement, try this
$sql = "INSERT INTO tblinbox VALUES ((SELECT id FROM tblscholar WHERE schoYear = '$newyearLevel'),'$sender','$type','$subject','$LRN','$content','$date', '$newyearLevel','','$userType')";
You can insert values either fetching values form another table or providing values as follows:
Way 1:
INSERT INTO tblinbox(coloumn_name1,coloumn_name2) VALUES (value1,value2);
Way 2:
INSERT INTO tblinbox(coloumn_name1,coloumn_name2) SELECT value1,value2 from tblscholer where schoYear= '$newyearLevel';
select cons_id,teh_id,local_id,panchayt_id,war_id,ha_id from b...;
select rep_value_id from val;`
i need to get the above values into single column in another table.
how can i solve it by a query or using stored procedure.
You can do something like this in oracle sql .
Insert into VAL_TABLE (ID,COMMON_FIELD) values (VAL_TABLE_ID.nextval, ( SELECT CONS_ID || TECH_ID || LOCAL_ID from TABLE_B));
Or in MySQL
Insert into VAL_TABLE (ID,COMMON_FIELD) values (1, ( SELECT concat( id, type, details) from TABLE_B ) );
Try this...
UPDATE my_table SET col1=
(SELECT CONCAT_WS(',',val.rep_value_id,cons_id,teh_id,local_id,panchayt_id,war_id,ha_id)
FROM b,val);
I have this Statement:
INSERT INTO qa_costpriceslog (item_code, invoice_code, item_costprice)
VALUES (1, 2, (SELECT item_costprice FROM qa_items WHERE item_code = 1));
I'm trying to insert a value copy the same data of item_costprice, but show me the error:
Error Code: 1136. Column count doesn't match value count at row 1
How i can solve this?
Use numeric literals with aliases inside a SELECT statement. No () are necessary around the SELECT component.
INSERT INTO qa_costpriceslog (item_code, invoice_code, item_costprice)
SELECT
/* Literal number values with column aliases */
1 AS item_code,
2 AS invoice_code,
item_costprice
FROM qa_items
WHERE item_code = 1;
Note that in context of an INSERT INTO...SELECT, the aliases are not actually necessary and you can just SELECT 1, 2, item_costprice, but in a normal SELECT you'll need the aliases to access the columns returned.
You can just simply e.g.
INSERT INTO modulesToSections (fk_moduleId, fk_sectionId, `order`) VALUES
((SELECT id FROM modules WHERE title="Top bar"),0,-100);
I was disappointed at the "all or nothing" answers. I needed (again) to INSERT some data and SELECT an id from an existing table.
INSERT INTO table1 (id_table2, name) VALUES ((SELECT id FROM table2 LIMIT 1), 'Example');
The sub-select on an INSERT query should use parenthesis in addition to the comma as deliminators.
For those having trouble with using a SELECT within an INSERT I recommend testing your SELECT independently first and ensuring that the correct number of columns match for both queries.
Your insert statement contains too many columns on the left-hand side or not enough columns on the right hand side. The part before the VALUES has 7 columns listed, but the second part after VALUES only has 3 columns returned: 1, 2, then the sub-query only returns 1 column.
EDIT: Well, it did before someone modified the query....
As a sidenote to the good answer of Michael Berkowski:
You can also dynamically add fields (or have them prepared if you're working with php skripts) like so:
INSERT INTO table_a(col1, col2, col3)
SELECT
col1,
col2,
CURRENT_TIMESTAMP()
FROM table_B
WHERE b.col1 = a.col1;
If you need to transfer without adding new data, you can use NULL as a placeholder.
If you have multiple string values you want to add, you can put them into a temporary table and then cross join it with the value you want.
-- Create temp table
CREATE TEMPORARY TABLE NewStrings (
NewString VARCHAR(50)
);
-- Populate temp table
INSERT INTO NewStrings (NewString) VALUES ('Hello'), ('World'), ('Hi');
-- Insert desired rows into permanent table
INSERT INTO PermanentTable (OtherID, NewString)
WITH OtherSelect AS (
SELECT OtherID AS OtherID FROM OtherTable WHERE OtherName = 'Other Name'
)
SELECT os.OtherID, ns.NewString
FROM OtherSelect os, NewStrings ns;
This way, you only have to define the strings in one place, and you only have to do the query in one place. If you used subqueries like I initially did and like Elendurwen and John suggest, you have to type the subquery into every row. But using temporary tables and a CTE in this way, you can write the query only once.
This question already has answers here:
How to do INSERT into a table records extracted from another table
(9 answers)
Closed 3 years ago.
As the title says, I am trying to insert into one table selecting values from another table and some default values.
INSERT INTO def (catid, title, page, publish)
(SELECT catid, title from abc),'page','yes')
INSERT INTO def (catid, title, page, publish)
VALUES
((SELECT catid, title from abc),'page','yes'))
The first query gives a mysql error and the second one gives column count does not match.
What do I need to do?
You simply have to do:
INSERT INTO def (catid, title, page, publish)
SELECT catid, title, 'page','yes' from `abc`
If you want to insert all the columns then
insert into def select * from abc;
here the number of columns in def should be equal to abc.
if you want to insert the subsets of columns then
insert into def (col1,col2, col3 ) select scol1,scol2,scol3 from abc;
if you want to insert some hardcorded values then
insert into def (col1, col2,col3) select 'hardcoded value',scol2, scol3 from abc;
INSERT INTO def (field_1, field_2, field3)
VALUES
('$field_1', (SELECT id_user from user_table where name = 'jhon'), '$field3')
If you you want to copy a sub-set of the source table you can do:
INSERT INTO def (field_1, field_2, field3)
SELECT other_field_1, other_field_2, other_field_3 from `abc`
or to copy ALL fields from the source table to destination table you can do more simply:
INSERT INTO def
SELECT * from `abc`
With MySQL if you are inserting into a table that has a auto increment primary key and you want to use a built-in MySQL function such as NOW() then you can do something like this:
INSERT INTO course_payment
SELECT NULL, order_id, payment_gateway, total_amt, charge_amt, refund_amt, NOW()
FROM orders ORDER BY order_id DESC LIMIT 10;