SQL Loops to insert dummy data? - mysql

Part of my job requires that I insert hundreds of fields into a table each week, and I'm getting honestly tired of doing it by hand. SQL is not my forte, so I was wondering if there could be a way to do it semi-automatically?
The query I need to fulfill is:
insert into [table] ([c1][c2][c3][c4][c5][c6])
values([v1][v2][v3][v4][v5][v6]);
Only v1 and v2 need to change each loop, 3 to 6 are always the same value. Could I somehow make an array for the values of v1 and v2 and make it so the query repeats itself advancing through those arrays? Or something that would save me an hour of manually replacing hundreds of values?
Thanks!

MySQL supports a syntax for INSERT INTO ... SELECT ... queries, which may do everything you want in one query.
Example: assuming you have two columns which always get the same string value (col1 + col2) and two columns with values from somewhere else:
INSERT INTO target_table
(col1, col2, col3, col4)
SELECT 'foo', 'bar', id, price
FROM source_table WHERE created_at > '2022-01-01';
That would insert the two static values "foo" and "bar" for each row, plus the values from id and price in source_table.

Related

how to check row number while importing data

We have database table 'field_data_body' and we are using 'insert into ... select from' mysql command to insert data into 'field_data_body' from another table.
Table structure:
In our database table, delta column is used to differentiate same record. For example,
In above exmaple, both row has same data except different value of delta.
How can we set delta while inserting data into database table?
I have search in google and some other questions in stack exchange but did not find solutions.
Thanks in advance.
You could use 2 queries for that.
insert into tablename (col1, col2, ..) Values (value1, value2, ..);
insert into tablename (delta) Values (value) where entity_type = 'node';

Select Insert Query by mentioning all columns across databases

I am working on redesigning of a legacy db and I have set new names to columns of old db. So, for instance, if olddb.oldtable under dbold has column descr, I have set it as description in new newdb.netable for column.
How can I mention individual columns in my query?
I am using MYSQL
Update: Both Databases are on different IP Addresses and I am using Navicat to transfer data.
You can try like this:
INSERT INTO newtable (col1, col2, ..., )
SELECT col1, col2, ..., FROM oldtable
By trying the above query you can insert the specific column. So for example if your newtable has a column as description and old table as descr then you can mention it like:
INSERT INTO newtable (col1, col2, `description`, ..., )
SELECT col1, col2, `descr` ,..., FROM oldtable
Also if the table column list is large and you want to copy all the columns and its data then you can simply use the wildcard charater * as:
INSERT INTO newtable
SELECT * FROM oldtable;
You can insert all columns at once without the need to mention the names using this:
INSERT INTO newtable (SELECT * FROM oldtable);
It will make an 1x1 match independently of column names.
If types don't match then will insert default values (not checked for all the type combination).
Note that column number must be the same on both tables otherwise an error like this will occur:
#1136 - Column count doesn't match value count at row 1

mySql insert needs all columns noted

I recently started hosting my own site and mySQL db. Everything works fine, but whenever I do an insert or update to any of tables, it errors out if I do not call out each and every column. Is there a setting for the table or the DB that controls this? I never had to do this with my previous DB host.
Thanks.
There are several ways to write an INSERT query.
INSERT INTO tablename (col1, col2, ...) VALUES (val1, val2, ...)
INSERT INTO tablename (col1, col2, ...) SELECT ...
INSERT INTO tablename VALUES (val1, val2, ...)
INSERT INTO tablename SELECT ...
In the first two methods, you don't have to list all the columns, since you specify the columns to be filled in explicitly. The columns that aren't in the (col1, col2, ...) list will get their default values. The VALUES list or the SELECT query must return as many columns as you specified in the list.
In methods 3 and 4, MySQL requires the VALUES list or the SELECT query to return as many columns as the table contains, and they must be in the same order as the table definition. I can't find any setting that disables the column count check in these methods.
In methods 1 and 3, you can put the keyword DEFAULT in place of any of the column values to insert its default value.
If your server is in STRICT mode, you also have to explicitly set any columns that do not have a DEFAULT option in the schema. If it's not in strict mode, automatic defaults will be used.
It probably doesn't fail if you UPDATE the values of some, but not all, columns in particular rows.
When you create your table, you need to set a default value for each column which you may choose to omit in your INSERT statements.

INSERT INTO where some of the data is dependent on a select

I understand how to do an insert into when all the input data is known, and I know how to do an insert into when all the data is dependent on a select, but I can't find how to do the in between. Where I'm at now:
INSERT INTO takes (stu_id, "CS-001", 1, "Autumn", 2009, null)
VALUES (SELECT id AS stu_id
FROM student
WHERE dept_name = "Comp. Sci.")
Thus I know all the other input data except the student's id, however MySQL just gives me a syntax error.
INSERT INTO takes (stu_id, col2, col3, col4, col5, col6)
SELECT id, 'CS-001', 1, 'Autumn', 2009, null
FROM student
WHERE dept_name = 'Comp. Sci.'
I don't know your destination column names - you have to replace them with the real ones in the query above.
Insert queries can be structured like this:
insert into table
(field1, field2, etc)
(value1, value2 etc)
or like this:
insert into table
(field1, field2, etc)
select this, that, etc
from etc
You tried to combine the two. That's one of the reasons you got an error.
juergen's answer is an example of the 2nd construct. His this and that is a combination of fields and constant values. That's perfectly ok. If you are getting syntax errors, it's in your details. His answer shows the right general idea.
It's often worthwhile to build your query step by step. Start with this:
insert into takes
(stu_id)
select id
from student
where dept_name = 'Comp. Sci'
If that works, add one field inside the brackets and whatever is appropriate to the select clause of your query. Keep going with these baby steps until you get it right. It's an approach I often take.

INSERT INTO with SubQuery MySQL

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.