Insert INTO table where one table has a NOT NULL - mysql

I have two identical tables bar one column, (one live, one test)
The test table has an extra not null Column called "MatchOrderNo"
I'm trying to extract data from Live to test, how can i populate this not Null for all rows?
basically my current statement is
INSERT INTO test SELECT * FROM live;

Depends what do you want to insert to the NOT NULL column? For a constant value :
INSERT INTO test
SELECT t.* , 'Val_For_NotNull_Col' FROM live t

You can use a Default value like:
INSERT INTO test SELECT live.col1, live.co2, '1' FROM live;

Related

Updating the timestamp of a row when copied from another table

I've been working at this for a while now and I haven't been able to come up with a solution, so i'm not sure if this may even be possible but any help is greatly appreciated.
I have two tables with a very basic structure as follows:
CREATE TABLE test ( time timestamp NULL DEFAULT NULL );
CREATE TABLE test_copy_to ( time timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP );
I then create an entry in the "test" table that has a NULL value i.e. no given time:
INSERT INTO test VALUES (NULL);
I then would like to copy the NULL value from the "test" table to the "test_copy_to" table as follows:
INSERT INTO test_copy_to SELECT * FROM test;
The first problem is that the "test_copy_to" won't accept NULL values which is what is initialized in the first table. However what I would like to achieve is being able to copy the value from "test" (while having the null value) to "test_copy_to" such that the time-stamp is updated to the time at which it was copied from one table to the other. I've tried using UPDATE on the variable time however that does not seem to work. Is there anyway I can create the table such that it behaves in this manner?
Instead use COALESCE() function like below to provide some default values where the value is null
INSERT INTO test_copy_to
SELECT coalesce(`time`, CURRENT_TIMESTAMP ) FROM test;

Duplicate all data in the same table MYSQL

I'm looking for a way I can duplicate all the rows in my database, I tried exporting it and then importing but I get the duplicate key error.
The reason is purely for testing purposes, I just want a load of dummy data in there to test the system I have out.
Is there a direct statement for this? Or is there a way to export all data except ID (or change ID to MAX(ID) + 1 or AUTO INCREMENT)?
You can try this:
INSERT INTO your_table_name(parent_id,priority,text,shortname,weighting,g_or_a,
dept,ksf,day_start,day_end,date_start,date_end,depends_on,is_question,budget,
ccode,responsible,accountable,consulted,informed)
(SELECT parent_id,priority,text,shortname,weighting,g_or_a,dept,ksf,
day_start,day_end,date_start,date_end,depends_on,is_question,budget,ccode,
responsible,accountable,consulted,informed FROM your_table_name);
Firstly, insert one row in the table 'your_table_name'. Replace your_table_name with the actual table name in above code & execute the code repeatedly until it satisfies the required row numbers. I think it should work.
Put 1 record and then run:
insert into mytable select * from mytable
10 times. This will give you 1024 records. Continue until satisfied.
You could use an INSERT and the values would be a SELECT, just don't select the primary key and don't define it in the insert fields.
Imagine a table with 3 fields, the_pk, field_1, field_2
Something like
INSERT INTO the_table(field_1, field_2) (SELECT field_1, field_2 FROM the_table)

inserting default value along with other columns

Hi help in this case i need to insert two columns in a table one column has to be default value as 'Other'(Please don't suggest to put Other as default value) and other column should get inserted from different table.
This is my sample code please suggest necessary change:
INSERT INTO table1 (`ID`,`specialty`)
SELECT `ID`,`here i need to put default value as other` from table2 a WHERE
Id IS NOT NULL
Do you mean this?
INSERT INTO table1 (ID,specialty)
SELECT ID, 'Other'
FROM table2
WHERE ID IS NOT NULL

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.

Copy from one column to another (different tables same database) mysql

Hi I would like to copy entire contents from column Item under table IName to column Name under table Item both belonging to the same database.
I am giving the following query but it throws the error saying that the subquery returned more than one records. (There are around 600 records)
Insert into Item set name = (Select Item from IName)
Thanks
INSERT INTO Item (Name)
SELECT Item
FROM IName
When you want to insert into a single-column* table, INSERT works either with:
INSERT INTO table (column)
VALUES (value1),(value2), ... (valueN) ;
or with:
INSERT INTO table (column)
SELECT a_column
FROM a_table
--- optional (multiple) JOINs
--- and WHERE
--- and GROUP BY
--- any complex SELECT query
(OK, the above can work with a multiple-column table, too, as long as all the other - not explicitely stated in the INSERT statement - columns have been defined with a DEFAULT value or with AUTO_INCREMENT.)
The INSERT ... SET syntax is valid in MySQL only and can be used only when you want to insert one row exactly:
INSERT INTO table
SET column = value1 ;
is equivalent to:
INSERT INTO table (column)
VALUES (value1) ;
INSERT INTO Item (name)
SELECT Item FROM IName
Link
INSERT INTO table_one (column1) SELECT column2 FROM table_two
See MySQL Ref