Resetting data in MySql database - mysql

I am faced with a scenario where I would like to remove all existing data from one of my tables and then reuse the table again and fill it with new data.
My Question: Should I destroy/recreate the exact same table to do this? Or is there an easier way? -Side Note: I am storing user id's and would like for the id's to be set back again as opposed to continuing at the number in which last data was stored.
I'm using PhpMyAdmin.

If you use TRUNCATE TABLE.
TRUNCATE TABLE empties a table completely. Logically, this is equivalent to a DELETE statement that deletes all rows, but there are practical differences under some circumstances.
...
it resets any AUTO_INCREMENT counter to zero
So if you want to keep the counter use DELETE FROM
If you delete all rows in the table with DELETE FROM tbl_name (without a WHERE clause) in autocommit mode, the sequence starts over for all storage engines except InnoDB and MyISAM.
You can also look here: How to prevent mySQL from resetting auto increment value?

You have to truncate your table, see documentation here: https://dev.mysql.com/doc/refman/5.0/en/truncate-table.html
In phpmyadmin there's a button in the table list called: Empty

Related

Adding a UNIQUE key to a large existing MySQL table which is receiving INSERTs/DELETEs

I have a very large table (dozens of millions of rows) and a UNIQUE index needs to be added to a column on that table. I know for a fact that the table does contain duplicated values on that key, which I need to clean up (by deleting rows/resetting the value of the column to something unique that I can automatically generate). A plus is that the rows which are already duplicated do not get modified anymore.
What would be the right approach to perform a change like this, given that I will be probably using the Percona pt-osc tool and there are continuous deletes/inserts on the table? My plan was:
Add code that ensures no dupe IDs get inserted anymore. Probably I need to add a separate table for this temporarily, since I want the database to enforce this for me and not the application - so insert into the "shadow table" with a unique index in a transaction together with my main table, rollback all inserts that try to insert duplicate values
Backfill the table by zapping all invalid column values which are within the primary key range below $current_pkey_value
Then add the index and use pt-osc to changeover the table
Is there anything I am missing?
Since we use pt-online-schema-change we are using triggers for performing the synchronisation from the existing table to a temp table. The tool actually has a special configuration key for this, --no-check-unique-key-change, which will do exactly what we need - agree to perform the ALTER TABLE and set up triggers in such a way that if a conflict occurs, INSERT .. IGNORE will be applied and the first row having used the now-unique value will win in the insert during synchronisation. For us this is a good tradeoff because all the duplicates we have seen resulted from data races, not from actual conflicts in the value generation process.

Truncate questions in SQL

How can I remove a row by using Truncate in SQL instead of delete by using WHERE condition?
Truncate only use to remove the table or row? if can remove the row by truncate, let me know anyone
You can't. Only DELETE statements can have a WHERE condition on them, TRUNCATE removes all rows.
From MSDN :
Removes all rows from a table or specified partitions of a table,
without logging the individual row deletions. TRUNCATE TABLE is
similar to the DELETE statement with no WHERE clause; however,
TRUNCATE TABLE is faster and uses fewer system and transaction log
resources.
You can only remove a single row with truncate if that row is the only one in the table.
Truncate is not like delete.
You can't use truncate to delete specific rows.
In fact, the statement is truncate table - you can't truncate anything other then a full table.
Truncate will remove all rows from the table, and is only allowed if the table is not referenced by foreign keys, is not used as the basis of an indexed view, and is not published by transactional replication or merge replication.
Also, truncate table can't be executed inside a transaction.
Truncate table will also reset the identity column of the table (if one exists).

re-inserting a table record and updating an auto increment primary index

I'm running MariaDB 5.5.56.
I'm looking to copy an entire row in a database, change one column, then insert the entire row back into the original database (I don't want to have to specify the individual fields because there's a lot of them). The problem I'm running into is how to deal with an auto-increment/primary key column.
example:
create temporary table t_ownership like ownership;
insert into t_ownership (select * from ownership where name='x' LIMIT 1);
update t_ownership set id='something else';
insert into ownership (select * from t_ownership);
I have a column "recno" that is an auto-increment that will create a collision in the database when I try to re-insert the slightly changed record back into the original table.
Something like this seems to work but doesn't result in an insert:
insert into ownership (select * from t_ownership) ON DUPLICATE KEY UPDATE recno=LAST_INSERT_ID(ownership.recno);
The above statement executes without error but does not add a row to table ownership.
So I think I'm close but not quite there...
What would be the best way to do this? I'd like to avoid doing an insert where I manually specify field/values. I just need to regenerate a new A.I. recno column on the insert.
NULL values inserted into auto-incremented fields end up just getting the next auto-increment value, behaving equivalent to INSERTing without specifying the field; so you should be able to update the source (temp copy) to have NULL for that field.
However, one potential issue that could present itself in scenarios like yours is that the CREATE TEMPORARY TABLE ... LIKE could result in a table that would not allow you to set such fields to NULL; this would require you to either ALTER the temporary table, or create it in a more explicit manner. Either way, it now makes code/queries that do not specify columns even more reliant on knowing columns.
Personally, I would take this route in the first place.
INSERT INTO theTable([list all but the auto-inc column])
SELECT [list all but the auto-inc column, with any replacements or modifications desired]
FROM ...[original query]...
It accomplishes the task in one query, makes the queries more self documenting, and only at the cost of a little typing (most of which a decent database browser, or query builder, will do for you).
The only argument really in favor of your current approach is that the table involved can be changed without necessarily breaking your queries; but that begs the question of whether it would be better for such table changes to break the queries, forcing them to be re-examined. If it is not an issue, it is a minor revision; but the alternative is queries that continue to be valid that have the potential to cause unexpected behavior due to copying information they were never intended to.

DELETE using TRUNCATE command and Delete VS. Truncate

Delete a single row of a table in MYSQL using truncate command difference between truncate and delete we can delete a single row but how to delete a single row using truncate?
You can't truncate a single row. Read up on the mysql reference:
TRUNCATE [TABLE] tbl_name TRUNCATE TABLE empties a table completely.
It requires the DROP privilege as of MySQL 5.1.16. (Before 5.1.16, it
requires the DELETE privilege).
Logically, TRUNCATE TABLE is equivalent to a DELETE statement that
deletes all rows, but there are practical differences under some
circumstances.
Reference:
13.1.34 TRUNCATE TABLE Syntax
Just for your knowledge DELETE is a DML Command. and TRUNCATE is a DDL command
No truncate can't be used for one single row. It has to be used for the entire table.
proper working/practical differences are :
With Delete command structure of the table is not purged from database.
you can delete all the data of the database but not the format of the table. that remains stable.
Delete is a DML command.
DELETE handles rows chosen with a WHERE statement. Its use is part of the discipline of running production applications. For example, you might DELETE all rows that have been marked "complete" more than a month ago.
Truncate removes/purge the structure of the table itself. It also purges sets the auto_increment to its initial value (that is zero by default).
Truncate is a DDL command
TRUNCATE rapidly removes all rows from a table while maintaining the table definition. (Row by row DELETE can take time, especially for tables with lots of keys.)
It comes in handy for such things as log tables that start out empty for each week's production.
It has the convenient side effect of resetting the indexes and releasing unused disk storage. I have used TRUNCATE to wipe out the contents of a log table that used to contain millions of rows, to switch to an operational discipline where it only contains a weeks' worth of rows, for example.
TRUNCATE removes all the rows from the Table.
DELETE statement deletes table rows and returns number of rows deleted.we can delete selected no of records from table using DELETE command.
TRUNCATE drops the table and re-create it. It is much faster than deleting rows one by one.
Once u use TRUNCATE command then u cannot retrieve the data again from the table.TRUNCATE removes all the rows from the Table.
Drop - deletes the data as well as structure.
The difference between DROP and DELETE table is that, after executing DELETE statement the contents of table are removed but the structure remains same, but in case of DROP statement both the contents and structure are removed.
When you want to delete a single row you use Delete command. When you want to clear the entire table data you can use Truncate Table command.

Why is MySQL creating tables with a _seq suffix?

I have created a InnoDB table named foo in MySQL. As soon as I perform an insert into the table, I see that another table foo_seq is created.
If I drop the auto generated table, it appears after the next insert.
What is causing this?
That sounds like a sequence is being created, do you have any autogenerated primary keys or IDs?
Issue this query, chances are very high it will tell you what happens before an insert:
SHOW TRIGGERS LIKE 'foo';