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
Related
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.
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
I am trying to import some value from a table to another table, the problem is that the 2 tables have a primary column id
So when I do INSERT INTO tab1 (SELECT * FROM tab2)
Duplicate entry 1 for key 'PRIMARY'
It says I can't because the id 1 already exists,
I don't really care about conserving the id, I just want to insert it at the end of tab1
So I had the id to do this (without the id column):
INSERT INTO tab1 (SELECT col2,col3 FROM tab2)
...etc but it says Column count doesn't match value count at row 1
How can I do to just insert evrything with a new id?
thanks in advance
This should work:
INSERT INTO table1 (col2, col3) SELECT table2.anothercol2, table2.anothercol3 FROM table2;
https://dev.mysql.com/doc/refman/5.0/en/insert-select.html
If you can alter the stucture of table 'tab1' you could set in 'tab1' an auto-increment field for primary and the other two fields accordingly to 'tab2'.
INSERT INTO tab1 (SELECT col2,col3 FROM tab2) should work then.
My table beers is made by:
userid, tohave
I use this:
INSERT INTO beers (userid,tohave) VALUES (1,1) ON DUPLICATE KEY UPDATE tohave=VALUES (tohave)
Is fine because the userid value (userid is PRIMARY) exists just updates the row but in my case if userid exists I want to add 1 to column tohave.
Is it possible doing it with one query?
Add +1?
INSERT INTO beers (userid,tohave)
VALUES (1,1) ON DUPLICATE KEY
UPDATE tohave = VALUES(tohave) + 1
Other answer on internet is not very clear, so I ask this question again.
Again, I have a table tb1
ID
114035
114035
How to delete 1 row & keep other?
The result should be
ID
114035
If you don't care about which one is removed:
DELETE FROM tb1 WHERE ID = 114035 LIMIT 1;
Otherwise find out what differentiates the one you want to keep and use that in the WHERE clause.
Try
ALTER IGNORE TABLE tb1 ADD UNIQUE INDEX idx_name (ID);
Add UNIQUE index to the column using ALTER and also use IGNORE keyword
This will delete duplicate entries and also no duplicate entry in future.
http://dev.mysql.com/doc/refman/5.1/en/alter-table.html
Update after OP's comment
Drop Unique constraint
DROP INDEX idx_name ON tb1
or
ALTER TABLE tb1 DROP INDEX idx_name
Consider using a temporary table to store the rows you don't want deleted.
CREATE TEMPORARY TABLE tmp ( id INT );
INSERT INTO tmp ( id )
SELECT id
FROM tbl
GROUP BY id
HAVING COUNT(1) > 1;
Then remove all of rows you consider to be duplicates.
DELETE FROM tbl
WHERE EXISTS(
SELECT 1
FROM tmp
WHERE tmp.id = tbl.id
);
Finally 'replace' the rows with the ones stored in the temporary table from earlier.
INSERT INTO tbl ( id )
SELECT id
FROM tmp;