Add deleted record to auto increment table - mysql

I have a table having id set to auto increment.
I have records 1 to 10 and I have deleted records 3 and 7.
So is their any way I can add records 3 and 7 again?

Yes, you have to "force" the id.
INSERT INTO table (id, field1) VALUES (3, "value"); // id = 3
But if you let the id "null" or not set, it will be incremented :
INSERT INTO table (field1) VALUES ("value"); // id = 8

In Mysql You can override the auto-increment id simply assingning the value you need .. this is perfectly legal ..
so you can insert your row with id 3 and 7 using
insert into your_table (id, col1, col2 ..) values (3, 'value_for_col1', 'value_for_col2'...)

the autoincrement only works if no value is specified for the field, in other words you can insert the specifying the value of the field with autoincrement, example: insert in db.banks (id, description,status, created_at,updated_at) values ('3', 'Central Bank', '1', '2017-04-14 10:30:22', null);

Related

INSERT IGNORE INTO multiple rows but on fail UPDATE [duplicate]

I want to add a row to a database table, but if a row exists with the same unique key I want to update the row.
For example:
INSERT INTO table_name (ID, NAME, AGE) VALUES(1, "A", 19);
Let’s say the unique key is ID, and in my Database, there is a row with ID = 1. In that case, I want to update that row with these values. Normally this gives an error.
If I use INSERT IGNORE it will ignore the error, but it still won’t update.
Use INSERT ... ON DUPLICATE KEY UPDATE
QUERY:
INSERT INTO table (id, name, age) VALUES(1, "A", 19) ON DUPLICATE KEY UPDATE
name="A", age=19
Check out REPLACE:
REPLACE works exactly like INSERT, except that if an old row in the table has the same value as a new row for a PRIMARY KEY or a UNIQUE index, the old row is deleted before the new row is inserted.
Example:
REPLACE INTO `tablename` (`id`, `name`, `age`) VALUES (1, "A", 19)
When using batch insert use the following syntax:
INSERT INTO TABLE (id, name, age) VALUES (1, "A", 19), (2, "B", 17), (3, "C", 22)
ON DUPLICATE KEY UPDATE
name = VALUES (name),
...
Any of these solution will work regarding your question:
INSERT IGNORE INTO table (id, name, age) VALUES (1, "A", 19);
or
INSERT INTO TABLE (id, name, age) VALUES(1, "A", 19)
ON DUPLICATE KEY UPDATE NAME = "A", AGE = 19;
or
REPLACE INTO table (id, name, age) VALUES(1, "A", 19);
Try this:
INSERT INTO table (id,name,age) VALUES('1','Mohammad','21') ON DUPLICATE KEY UPDATE name='Mohammad',age='21'
Note:
Here if id is the primary key then after first insertion with id='1' every time attempt to insert id='1' will update name and age and previous name age will change.
Try this out:
INSERT INTO table (id, name, age) VALUES (1, 'A', 19) ON DUPLICATE KEY UPDATE id = id + 1;
Hope this helps.
In case that you wanted to make a non-primary fields as criteria/condition for ON DUPLICATE, you can make a UNIQUE INDEX key on that table to trigger the DUPLICATE.
ALTER TABLE `table` ADD UNIQUE `unique_index`(`name`);
And in case you want to combine two fields to make it unique on the table, you can achieve this by adding more on the last parameter.
ALTER TABLE `table` ADD UNIQUE `unique_index`(`name`, `age`);
Note, just make sure to delete first all the data that has the same name and age value across the other rows.
DELETE table FROM table AS a, table AS b WHERE a.id < b.id
AND a.name <=> b.name AND a.age <=> b.age;
After that, it should trigger the ON DUPLICATE event.
INSERT INTO table (id, name, age) VALUES(1, "A", 19) ON DUPLICATE KEY UPDATE
name = VALUES(name), age = VALUES(age)
Just because I was here looking for this solution but for updating from another identically-structured table (in my case website test DB to live DB):
INSERT live-db.table1
SELECT *
FROM test-db.table1 t
ON DUPLICATE KEY UPDATE
ColToUpdate1 = t.ColToUpdate1,
ColToUpdate2 = t.ColToUpdate2,
...
As mentioned elsewhere, only the columns you want to update need to be included after ON DUPLICATE KEY UPDATE.
No need to list the columns in the INSERT or SELECT, though I agree it's probably better practice.
When using SQLite:
REPLACE into table (id, name, age) values(1, "A", 19)
Provided that id is the primary key. Or else it just inserts another row. See INSERT (SQLite).
In case, you want to keep old field (For ex: name). The query will be:
INSERT INTO table (id, name, age) VALUES(1, "A", 19) ON DUPLICATE KEY UPDATE
name=name, age=19;
In my case i created below queries but in the first query if id 1 is already exists and age is already there, after that if you create first query without age than the value of age will be none
REPLACE into table SET `id` = 1, `name` = 'A', `age` = 19
for avoiding above issue create query like below
INSERT INTO table SET `id` = '1', `name` = 'A', `age` = 19 ON DUPLICATE KEY UPDATE `id` = "1", `name` = "A",`age` = 19
may it will help you ...
Following are some of the possible approaches:
Using INSERT INTO
The INSERT statement allows you to insert one or more rows into a table
First, specify the table name and a list of comma-separated columns inside parentheses after the INSERT INTO clause.
Secondly, put a comma-separated list of values of the corresponding columns inside the parentheses following the VALUES keyword.
INSERT INTO table_name(column_name1, column_name2, column_name3) VALUES("col_value_1", "col_value_2", "col_value_3");
Using INSERT INTO with WHERE NOT EXISTS clause
INSERT INTO table_name (column_name_1, column_name_2, column_name_3)
SELECT * FROM (SELECT "col_value_1", "col_value_2","col_value_3") AS tmp_name
WHERE NOT EXISTS (
SELECT column_name2 FROM table_name WHERE column_name = "sample_name"
) LIMIT 1;
Using REPLACE INTO
REPLACE works exactly like INSERT, except that if an old row in the table has the same value as a new row for a PRIMARY KEY or a UNIQUE index, the old row is deleted before the new row is inserted.
REPLACE INTO table_name(column_name1, column_name2, column_name3) VALUES("col_value_1", "col_value_2", "col_value_3");

Insert type id in table

How to insert score with value and score_id ? At server im know only score_type.name and score.value. How i can insert new score with score_type ? If score_type name exsist just get id and insert, else create, get id and insert.
First try to create the score_type if it doesn't exist:
INSERT IGNORE INTO score_type (name) VALUES ("type_name");
Then use INSERT ... SELECT to insert the ID into the score table:
INSERT INTO score (value, score_type_id, player_id)
SELECT 123, id, "player_name"
FROM score_type
WHERE name = "type_name";
The first INSERT assumes you have a unique index on score_type.name. IGNORE means to fail silently if you try to insert a duplicate name.
Replace 123 and player_name with the known score.value and score.player_id.
If I understood your question correctly, you want to fill the score_type_id dynamically by selecting it using the name:
INSERT INTO `score`(`value`, `score_type_id`, `player_id`) VALUES (1337, (SELECT id FROM score_type WHERE score_type.name = "test") ,"maio290");
The trick is just to use another query instead of a fixed value.

Inserting data into table SQL server

If I have 2 tables and Table 1 has a primary key(userID) AutoIncrement and Table 2 has a foreign Key(userID) to Table 1's (userID)
When I insert a new row into Table 1 first row will have userID = 1
Then if I insert again, userID = 2.
So how do I go about keeping Table 2's userID the same when inserting in Table 1. For instance, in Table 2, I am adding the password into another table.
My question is should I add an AUTOINCREMENT to Table 2(userID) and insert a new value into both tables when I create a user OR is there another way?
You have to manually insert data with correct id in Table2. There is no such built-in functionality in MySQL.
The algorithm is as follows:
Insert row in Table1.
Get Id of the new row.
Insert row with new id in Table2.
I think what you are looking for is this ... Assuming your ID is PK and AI
INSERT INTO yourTable (var1, var2 etc etc) VALUES ('val1', 'val2' etc etc);
SELECT LAST_INSERT_ID();
To further it ..
INSERT INTO yourTable (var1, var2 etc etc) VALUES ('val1', 'val2' etc etc);
SET #last_id = LAST_INSERT_ID();
INSERT INTO yourTable2 (id, var1, var2) VALUES (#last_id, 'blah', 'blah');

mysql update multiple id/value pairs with one statement

If I have a mysql table with the 2 columns:
ID Date
1 2012-03-05
2 2012-02-21
3 2013-06-12
4 2011-01-15
5 2013-02-23
and I have an array of random updates such as
$arr = array('2'=>'2013-03-23','4'=>'2013-03-19','5'=>'2011-08-09');
(where the index is the ID and the value is the date)
is there a way to update the table with one statement?
the reason I am doing this, is because I need to make hundreds+ of changes and single updates would be alot of statements.
If ID is unique or a primary key, you can do
INSERT INTO `Table` (ID, `Date`)
VALUES ('2', '2013-03-23'), ('4', '2013-03-19'), ('5', '2011-08-09')
ON DUPLICATE KEY UPDATE `Date` = VALUES(`Date`)
Note that this might affect the auto increment value and it might insert new records into the table.

MySql: REPLACE INTO with number=number+1

I would like do something like this in one only query.
REPLACE INTO table ( id, number ) VALUES ( 'test', number=number+5 )
What I want is (the first time!) insert the row and set the number 5.
the other times (if already exist) add 5 at the number.
Is it possible? I can't find nothing on line.
just be sure that ID is unique. Use INSERT ... ON DUPLICATE KEY UPDATE Syntax
INSERT INTO tableName (id, number)
VALUES ('test', 5)
ON DUPLICATE KEY UPDATE
number = number + 5
Assuming that id is a proper key (e.g. primary key):
INSERT INTO `table` (id, number)
VALUES ('test', 5)
ON DUPLICATE KEY UPDATE number=number+VALUES(number)