mysql command to insert new rows between old rows - mysql

i have a table with much data in it. the id is set as a primary with AUTO_INCREMENT function. how can i insert a new row like
INSERT INTO `medikamente`(`id`, `Augmentin`, `Ciproxin`, `Klacid`, `Voltaren`, `Seractil`, `Mexalen`, `Aspirin`, `Thomapyrin`, `Esomeprazol`, `Omeprazol`, `Nexium`, `Pantoloc`, `Guttalax`, `indikator`, `indikator2`)
VALUES (NULL,'','','','','','','','','','','','','','','');
lets say between id 5 and id 6? i don't want to change the id's manualy to have a free row between that id's. how can i do that over an command?
br

You can get free place in id sequence by query:
UPDATE medikamente SET id = id + 1 WHERE id > 5 ORDER BY id DESC;
After you can use id 6 for insert new row:
INSERT INTO `medikamente`(
`id`, `Augmentin`, `Ciproxin`, `Klacid`, `Voltaren`, `Seractil`, `Mexalen`, `Aspirin`, `Thomapyrin`, `Esomeprazol`, `Omeprazol`, `Nexium`, `Pantoloc`, `Guttalax`, `indikator`, `indikator2`
) VALUES (
6,'','','','','','','','','','','','','','',''
);
Be carefully if you table have foreign keys.

Related

Insert and fill a non restricted field with the new unique key autoincrement id value

I have a table with two fields:
Unique Id autoincrement -> Id
int -> copyOfId
Id can be written manually, or can be assigned by database but copyOfId.
To set the same value to Id and copyOfId, I can do this:
set #nextId = (select id from table order by id desc limit 1) + 1;
insert into table (Id,...,...,...,copyOfId,...,...,...
) VALUES (
#nextId,...,...,...,#nextId,...,...,...);
Is it possible to set the copyOfId with the same Id on an Insert automatically?
Is it possible to set the copyOfId with the same Id on an Insert automatically?
No. Neither BEFORE trigger nor generated column may refer to autoincremented column.
But you may remove autoincrementing, create separate table with autoincremented column, and set both id and its copy from BEFORE trigger.
Example fiddle with some explanations.
Pay attention - the values for id and its copy provided in INSERT will be overwritten unconditionally. If you need to set them manually to some N then insert a row with N-1 value (which must be above current maximal value) into additional table explicitly then insert into working table.
Do not update PK value in working table with the value above current maximal value.

Insert or Update with mysql if same two column

I have a table to store client's answers.I want to use one mysql query to insert or update this table.
My Table name : questionform_answer
and columns > ClientID QuestionID OptionID
Each client can only have one same question id.For example
ClientID QuestionID OptionID
1 1 1
1 2 5
2 1 3
I want to update OptionID if already exist ClientID and QuestionID.I don't want to use select query so taking so time.
I tried
ON KEY UPDATE
Replace Into
But I could not.
I use php so I tried first update query and if mysqli return fail insert row but it is also slow.
MY insert and update code :
Insert Into questionform_answer (ClientID,QuestionID,OptionID) values
('$ClientID','$soruid','$cevapid')
Update questionform_answer set OptionID='$cevapid' where
ClientID='$ClientID' and QuestionID='$soruid'
One way around this is to add a unique key over (ClientID, QuestionID) and use an INSERT ... ON DUPLICATE KEY UPDATE query:
ALTER TABLE table1
ADD UNIQUE INDEX (ClientID, QuestionID);
INSERT INTO table1
VALUES (1, 1, 4)
ON DUPLICATE KEY UPDATE
OptionID = VALUES(OptionID)
Demo on dbfiddle
First of all, you should use prepared statements to avoid SQL injections.
If you have a unique key on (ClientID,QuestionID), you can do INSERT INTO ... ON DUPLICATE KEY like this:
INSERT INTO questionform_answer (ClientID,QuestionID,OptionID)
values ('$ClientID','$soruid','$cevapid')
on duplicate key update OptionID='$cevapid'

insert a new record into a mysql table with one of the values incremented by 1

I've got the following table:
productId price
1 price_value1
2 price_value2
3 price_value3
I would like to insert a new product into the table and assign it a new productId. In this case its value equals to 4.
So I want my new table to look like so:
productId price
1 price_value1
2 price_value2
3 price_value3
4 price_value4
So as far as I understand, in order to do that I have to somehow retrieve the max value of productId and insert it using INSERT INTO mytable VALUES (productId + 1, price_value4).
But how do I find out the maximum value of productId?
I tried INSERT INTO mytable VALUES (SELECT MAX(productId) + 1 FROM mytable, price_value4) but it didn't work.
This should Work:
Select the max(productID) and price_value4 as a columns from mytable and insert the result.
INSERT INTO mytable (SELECT MAX(productId) + 1, 'price_value4' FROM mytable);
However, if you are not going to jump some number you can just add an auto increment id key to product_id and then you will have only to insert the price, the product ID will be incremented automatically..
This will do so :
ALTER TABLE mytable
MODIFY COLUMN `productId` INT(10) UNSIGNED PRIMARY KEY AUTO_INCREMENT;
you can change INT(10) with the INT(5) for example depanding on the size you want to give to your productId column
EDIT :
In return to the OP question in comments why his solution wouldn't work
Some suggetions says you have to make the SELECT statment in insert always between parenthesis
INSERT INTO mytable VALUES ( (SELECT MAX(ID)+1 FROM mytable) , price_value4)
.. In my Case it Return
(1093): You can't specify target table
'mytable' for update in FROM clause
AND HERE IS WHY (Quoting From the documentation)
When selecting from and inserting into the same table, MySQL creates
an internal temporary table to hold the rows from the SELECT and then
inserts those rows into the target table. However, you cannot use
INSERT INTO t ... SELECT ... FROM t when t is a TEMPORARY table,
because TEMPORARY tables cannot be referred to twice in the same
statement
BUT there is away to overcome by using a query instead of the table itself in the FROM, which has the effect of copying the requested table values instead of referencing the one that you are updating..
INSERT INTO mytable VALUES (
(SELECT MAX(ID)+1 FROM (SELECT * FROM mytable ) as mytmp ),
'price_value4');
OR (Quoting From the documentation)
To avoid ambiguous column reference problems when the SELECT and the
INSERT refer to the same table, provide a unique alias for each table
used in the SELECT part, and qualify column names in that part with
the appropriate alias.
INSERT INTO mytable Values ( (SELECT MAX(ID)+1 FROM mytable as mytmp) , 'price_value4')
This is a duplicate question. In order to take advantage of the auto-incrementing capability of the column, do not supply a value for that column when inserting rows.
A simple syntax to create table
CREATE TABLE Product (
productId MEDIUMINT NOT NULL AUTO_INCREMENT,
price INT NOT NULL,
PRIMARY KEY (productid)
);
While inserting supplied default or leave column as blank or supplied value as NULL. Take a look at below code snippet.
INSERT INTO Product (price) VALUES
('10'),('20'),('4'),
('30');
refer this link

How to insert if not exists with selecting from same table?

I have my table schema in H2 db as follows:
create table if not exists Test ( id bigint not null,name varchar(255), primary key (id) );
alter table Test add constraint if not exists Test_NAME UNIQUE (name);
I want to insert a value for the name attribute as 'Default' if it does not exist in the table by selecting the latest id value from the table and increment it by one.
Example:
Do not insert if an entry for name = Default already exists.
ID | Name
1 | Default
Insert if an entry for name = Default does not exists.
ID | Name
1 | ABC
2 | XYZ
For the id column, find the max id and increment it by one. In this case, insert id=3 and name=Default.
My query is as follows:
INSERT INTO Test (id , name)
SELECT max(id) + 1, 'Default' from Test
WHERE NOT EXISTS (SELECT * FROM Test where name='Default');
However, it gives me an error saying:
NULL not allowed for column "ID"; SQL statement
as it applies the where condition on the inner select statement.
I also tried:
MERGE INTO Test KEY(name) VALUES (SELECT MAX(id) + 1 from Test, 'Default');
It gives an error because, merge tries to update with the new values.
If it finds 'Default', it will update the row with new id causing primary key violation.
Is there a better way to do this? How can I make the query work?
You are massively overcomplicating this. Define the id field as auto increment and place a unique index on the name field. The unique index prevents duplicate names to be inserted, while the auto increment increases the value of the id field by 1 (by default) if the insert is successful.
I updated id to auto increment and the following query work flawlessly
INSERT INTO Test (name) select * from (select 'Default') as tmp WHERE NOT EXISTS (SELECT name from Test where name='Default');
when you run your query first time, no record found in table so, it give error 'null' there, so if you add IFNULL() function there as below
INSERT INTO Test (id , name)
SELECT **IFNULL**(max(id),0) + 1, 'Default'
FROM Test
WHERE NOT EXISTS (SELECT * FROM Test where name='Default');

SQL shift all subsequent rows

I have a table where each row has a primary key ID (ordered ASC), which is just a number. Is there a way to insert a row between two others by first shifting all of the rows below it by one?
Yes you can like you want to insert row with id 2 you can do so
CREATE TABLE Table1
(id INT,`test` varchar(10))
;
INSERT INTO Table1
(id,`test`)
VALUES
(1,'val'),
(2,'val'),
(3,'val')
;
Demo table has 3 records and id 2 is already assigned now you want to add row for id 2 and increment all the ids by 1
update Table1
set id =id+1
where id >1
ORDER BY id DESC;
INSERT INTO Table1
(id,`test`)
VALUES
(2,'my val');
In update query ORDER BY id DESC is necessary for primary key to ignore the duplicate entry error
SELECT * FROM Table1 order by id
Fiddle Demo