How to add Identity column into existing table in SQL? [duplicate] - mysql

I have an old MS Access DB which I'm translating to a MySQL DB. I used bullzip to create the database but due to bad design the old MS Access database didn't have a unique primary key for most of the tables.
So I've created a id field but obviously it's empty for each entry, I wonder if there's a simple statement I can use to fill them up with 1, 2, 3, 4 etc...
EDIT:
I think I haven't gotten my question across properly. I know all about auto increment. Thats not the problem.
I have a table, full of records which I need kept and which came from a Access database that didn't have a unique id defined as a field. In otherwords I have fields for firstname, surname etc etc but no field 'id'. This seems absolutely crazy but apparently this database has been well used and never had any unique ids for any tables bar one. Weird!
Anyway, I've created a field in the table for id (and set it to auto increment of course) but obviously all the existing records don't have an id set currently. So I need to create one for each record.
Is there a way to fill all these records with unique numbers using a mysql statement?
Cheers

If you add an new id column to an existing table and make it AUTO_INCREMENT PRIMARY KEY, it will automatically populate it with incrementing values.
mysql> ALTER TABLE TheTable ADD COLUMN id INT AUTO_INCREMENT PRIMARY KEY;
mysql> SELECT id FROM TheTable;
-- outputs values 1, 2, 3, etc.
If you made an id column but didn't declare it AUTO_INCREMENT PRIMARY KEY, you can populate the column like this:
mysql> SET #id := 0;
mysql> UPDATE TheTable SET id = (#id := #id+1);

Use a predefined AUTO_INCREMENT field, and set the value as NULL when inserting new records, so that it automatically builds up an appropriate incrementer. Aside from that, there is no way (unless using a procedure) to create an incrementing set of values

Use the auto_increment feature of MySQL. MySQL will generate unique numbers for your id column.
For an explanation of the auto_increment feature see http://dev.mysql.com/doc/refman/5.0/en/example-auto-increment.html

If you just want a unique identifier, you can use the uuid() function. It takes up a bit more space than an integer, but it does what you want.
However, I agree with the other answers that you should add an auto increment column and repopulate the table. That is the simplest way to keep the ids unique over time, even as updates takes place, and using a more reasonable amount of storage.

I am not proficient in MySQL, but I have faced this same problem in other DBMS's and here is how I have addressed it when there was an AutoIncrement type facility, but the DBMS had no way to automatically apply it retroactively:
Rename the table you want to add the ID field to. So rename Table1 to Table1_Old.
Create a new Table1 that is a copy of Table1_Old except that it has no data in it.
Add your ID/AutoIncrement column to Table1
Now copy all of the data from Table1_Old to Table1, either skipping or specifying NULL for the ID column. (This is usually a single INSERT..SELECT.. command)
Drop Table1_Old.
The actual specifics and commands vary from DBMS to DBMS, but I have usually been able to find a way to do these steps.

Use AUTO_INCREMENT
CREATE TABLE insect
(
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
PRIMARY KEY (id),
name VARCHAR(30) NOT NULL,
date DATE NOT NULL,
origin VARCHAR(30) NOT NULL
);
Update
I believe, it seems tough task unless you won't create new table, I will suggest you to use this
SET #rank=0;
SELECT #rank:=#rank+1 AS rank, itemID FROM orders;
It will create a virtual column with the name rank for you, which have unique id value.

Related

MySQL auto increment based on field?

Is it possible to create auto-increment based on a specific field? For example i have UserId and Status fields, so for each row with same UserId i need to auto-increment its Status, not global.
There is three thing that come to mind when I read your question. One was an auto incrementing field which acts as your ID number. Updating a table with data that has no unique ID number. Searching for fields with the same Userid to Status
Mt First example is of a creating a table and your AUTO_INCREMENTing number ID:
CREATE TABLE tableNameHere
(
UniqueID int NOT NULL AUTO_INCREMENT,
FirstName varchar(255) NOT NULL,
StatusOrYourColumn int(100) NOT NULL,
PRIMARY KEY (UniqueUD)
)
More on auto incrementation.
You may have already built your table and now want to 'add' additional and or modify your fields using ALTER:
ALTER TABLE tableNameHere StatusOrYourColumn INT AUTO_INCREMENT PRIMARY KEY
But be careful, you don't want to overwrite your settings that you have already set.
Another Thing that came to my mind when reading was where you said Status and Userid where the same. You can find these using the WHERE clause like so:
SELECT * FROM tableName WHERE tableName.Userid = anotherTableOrTableName.Status
Using these queries you can update, remake, alter and query your database table.

Creating MySQL table with distinct id:s

I'm using MySQL in PHPMyAdmin. I would like to create table where one can find distinct id's for every user. Can this be done by auto_increment, like
`user_id` SMALLINT NOT NULL AUTO_INCREMENT PRIMARY KEY
or what does the auto_increment mean?
Yes, that would work. AUTO_INCREMENT means that every time you add a new row, it automatically makes the id the previous + 1. You also don't specify a user_id when you add a new user.
auto increment means that mysql automatically creates the value in the field and increments it by 1 every new record.
You don't have to manage that at all.
Hmmm...maybe I misunderstood the question. If you make the drop down for the "extra" field in phpMyAdmin "auto_increment" it will make it auto increment the field value as described above.
That should cover it :o)
AUTO INCREMENT means that you don't need to fill this field, it will be filled automatically.
If you want find distinct id you should make it PK (primary key) or unique. Both of them make this values distinct

Reset the row number count in SQLite3/MySQL

I am using SQLite3. I load a table with say 30 rows using integer as Primary ID and it auto-increments.
Now I delete all the rows from the table and then, reload some new information onto the table.
Problem is: the row count (my PrimaryID) now starts with 31. Is there any way that I can start loading new rows from the number 1 onwards?
SQLite
Use:
DELETE FROM your_table;
DELETE FROM sqlite_sequence WHERE name = 'your_table';
Documentation
SQLite keeps track of the largest ROWID that a table has ever held using the special SQLITE_SEQUENCE table. The SQLITE_SEQUENCE table is created and initialized automatically whenever a normal table that contains an AUTOINCREMENT column is created. The content of the SQLITE_SEQUENCE table can be modified using ordinary UPDATE, INSERT, and DELETE statements. But making modifications to this table will likely perturb the AUTOINCREMENT key generation algorithm. Make sure you know what you are doing before you undertake such changes.
Found the answer on SO: SQLite Reset Primary Key Field
MySQL
Use:
ALTER TABLE tbl AUTO_INCREMENT = 1;
In either case, the database doesn't care if the id numbers are sequencial - only that the values are unique. If users never see the primary key value (they shouldn't, because the data can change & won't always be at that primary key value), I wouldn't bother with these options.
For MySQL:
Use TRUNCATE TABLE tablename to empty the table (delete all records) and reset auto increment count.
You can also use ALTER TABLE tablename AUTO_INCREMENT = 0; if you just want to reset the count.
For SQLite:
DELETE FROM tablename;
DELETE FROM SQLITE_SEQUENCE WHERE name='tablename';
References
SQLite AutoIncrement
MySQL AutoIncrement
For SQLite use (not need to delete and create the table)
UPDATE SQLITE_SEQUENCE SET SEQ=0 WHERE NAME='table_name';
For MySql use
ALTER TABLE table_name AUTO_INCREMENT = 1;
You should not use AUTOINCREMENT in this case. Simply define your primary key as INTEGER PRIMARY KEY and the count will be reset to 1 after a DELETE FROM query. Without AUTOINCREMENT, the default behaviour will still be an automatic increment of the primary key as long as you don't run out of space in your table (in that case, old - deleted - values will be reused).
More information available in the SQLite Autoincrement document.
ALTER TABLE tbl AUTO_INCREMENT = 0;

mysql manual increment ids?

I have a table with items in it (id, name, etc) and I want some kind of database scheme to be able to have multiple copies of the item while still being able to increment the ids. There will be a field called startdate or date_from_which_this_entry_should_be_used.
I've thought of two ways of implementing this:
Have a table with only ids (primary key, auto-increment) and do joins to a table that has all the item information.
Advantages:
easy to understand
hard for someone that comes after me to get confused
Disadvantages:
requires more debugging and coding since this system is already in use
seems weird to have a table with a single field
Have a single table using a sub-select to get the MAX value (+1) to apply to new items.
Advantages:
single table
only minor code adjustments (but not all that different, maybe)
Disadvantages:
prone to errors (manual increment, can't allow deletions or the MAX value might be off)
Thanks in advance!
You should create a table called item_ids or something to generate id values. It's okay that this has only a single column.
CREATE TABLE item_ids (
item_id INT AUTO_INCREMENT PRIMARY KEY
) ENGINE=InnoDB;
You don't even need to commit any data to it. You just use it to generate id values:
START TRANSACTION;
INSERT INTO item_ids DEFAULT VALUES;
SET #id = LAST_INSERT_ID();
ROLLBACK;
So now you have a concurrency-safe method to create new id's.
Then you make a compound primary key for your items table. You must use MyISAM for this.
CREATE TABLE items (
item_id INT,
seq_id INT AUTO_INCREMENT,
name VARCHAR(20),
etc VARCHAR(20),
PRIMARY KEY (item_id, seq_id)
) ENGINE=MyISAM;
MyISAM supports an auto-increment column in a compound primary key, which will start over at value 1 for each new item_id.* It also uses MAX(item_id)+1 so if you delete the last one, its value will be reallocated. This is unlike other use of AUTO_INCREMENT where a deleted value is not re-used.
Whether you insert a new item, or whether you insert a new copy of an existing item, you use a similar INSERT:
INSERT INTO items (item_id, name, etc) VALUES (#id, 'Stephane', 'etc');
The #id parameter is either a value of an existing item, or else the auto-generated value you got from the item_ids table.
* InnoDB supports auto-increment only as the first column of a primary or unique key, and it does not start over the count for each distinct value of the other column.

SqlServer create table with MySql like auto_increment primary key

I want to make a table in SqlServer that will add, on insert, a auto incremented primary key. This should be an autoincremented id similar to MySql auto_increment functionality. (Below)
create table foo
(
user_id int not null auto_increment,
name varchar(50)
)
Is there a way of doing this with out creating an insert trigger?
Like this
create table foo
(
user_id int not null identity,
name varchar(50)
)
OP requested an auto incremented primary key. The IDENTITY keyword does not, by itself, make a column be the primary key.
CREATE TABLE user
(
TheKey int IDENTITY(1,1) PRIMARY KEY,
Name varchar(50)
)
They have answered your question but I want to add one bit of advice for someone new to using identity columns. There are times when you have to return the value of the identity just inserted so that you can insert into a related table. Many sources will tell you to use ##identity to get this value. Under no circumstances should you ever use ##identity if you want to mantain data integrity. It will give the identity created in a trigger if one of them is added to insert to another table. Since you cannot guarantee the value of ##identity will always be correct, it is best to never use ##identity. Use scope_identity() to get this value instead. I know this is slightly off topic, but it is important to your understanding of how to use identity with SQL Server. And trust me, you did not want to be fixing a problem of the related records having the wrong identity value fed to them. This is something that can quietly go wrong for months before it is dicovered and is almost impossible to fix the data afterward.
As others have mentioned: add the IDENTITY attribute to the column, and make it a primary key.
There are, however, differences between MSSQL's IDENTITY and MySQL's AUTO_INCREMENT:
MySQL requires that a unique
constraint (often in the form of a
primary key) be defined for the
AUTO_INCREMENT column.MSSQL doesn't have such a requirement.
MySQL lets you manually insert values into an AUTO_INCREMENT column.
MSSQL prevents you from manually inserting a value into an IDENTITY
column; if needed, you can override
this by issuing a "SET
IDENTITY_INSERT tablename ON"
command before the insert.
MySQL allows you to update values in an AUTO_INCREMENT column.MSSQL refuses to update values in an
IDENTITY column.
Just set the field as an identity field.
declare the field to be identity
As advised above, use an IDENTITY field.
CREATE TABLE foo
(
user_id int IDENTITY(1,1) NOT NULL,
name varchar(50)
)
As others have said, just set the Identity option.