How to create an AutoNumber field value in Access? - ms-access

I'm trying the following:
CREATE TABLE Table1
(
RecordNo autonumber, --error here!
PersonId varchar(50),
...
)
But, there is an error.
How can I build the correct query in Access?

According to SQL Auto Increment a Field:
CREATE TABLE Persons
(
P_Id PRIMARY KEY AUTOINCREMENT,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)
The MS Access uses the AUTOINCREMENT
keyword to perform an auto-increment
feature.
By default, the starting value for
AUTOINCREMENT is 1, and it will
increment by 1 for each new record.
To specify that the "P_Id" column
should start at value 10 and increment
by 5, change the autoincrement to
AUTOINCREMENT(10,5).
Synonyms for AUTOINCREMENT include COUNTER and IDENTITY. Using IDENTITY the makes a lot of sense because it matched the #IDENTITY variable which returns the last used autonumber value.

The order might be important
CREATE TABLE Persons
( pkObject AUTOINCREMENT PRIMARY KEY)
If I try PRIMARY KEY AUTOINCREMENT as suggested, it gets upset (MSAccess 2010).

Method 1:
Open table in design view
Make a field named "ID" or whatever the field will be that will have the Auto Increment
Put "AutoNumber" under DataType
Method 2:
Make a new table
Close the table and save it
When it asks if you want a primary key click ok
Open the table in Design View
Edit the new field to whatever name you like

When using ancient DAO 3.60 and Jet 4.0 with Access 2003 files, Eugene Yokota'a syntax did not work. I found that COUNTER keyword will do the trick:
CREATE TABLE tablename(id COUNTER, Name Text (30))
Thanks to this post:
http://www.vbforums.com/showthread.php?234335

Related

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

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.

SQL: Add new Primary Key Column to Database Table

I have a database table with several columns where some of them used to form the primary key together. Now the model changed and a single primary key column, called 'id', gets introduced.
When I alter the table and add the column, the column gets populated in every row with an default value, 0 or NULL, so that it can not be used as a candidate for a new primary key. To achieve that, I have to have a different (numerical) value for 'id' in every row. How can I achieve that, preferably as generic as possible (MySQL, Oracle, SQL Server).
Here is a sample of how to add an identity column that populates as a primary key.
create table #t (vals varchar(100))
insert into #t
values('a'),('b'),('c')
alter table #t
add ID int identity primary key
select * from #t
Results:
vals ID
a 1
b 2
c 3
This is a SQL Server answer. I don't know how the other databases work.
CREATE TABLE Persons (
ID int IDENTITY(1,1) PRIMARY KEY,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int
);
Might be this will be helpful.
The MS SQL Server uses the IDENTITY keyword to perform an auto-increment feature.
In the example above, the starting value for IDENTITY is 1, and it will increment by 1 for each new record.
Tip: To specify that the "ID" column should start at value 10 and increment by 5, change it to IDENTITY(10,5).
To insert a new record into the "Persons" table, we will NOT have to specify a value for the "ID" column (a unique value will be added automatically):

Existing table add auto increment primary key - sql

I have an existing product table which is already populated with 120 records and I have tried below SQL query:
ALTER TABLE product ADD product_id
INT PRIMARY KEY AUTO_INCREMENT
But it's given me the error:
Error: #1075 - Incorrect table definition; there can be only one auto column and it must be defined as a key
Here is work around
create a simple column with autoincrement
browse the table and again make this newly added column as primary key
You are done !
:) Thanks to Guy who is not in Stackoverflow
Friend
If you try to do this in MSSQL then your script will be this.
suppose your table is below
create table product
(
name varchar(20),
product_type varchar(20)
)
and suppose you entered some record in this table after that you want to add a column that name product_id with auto increment and primary key. Then you use this script that is below
alter table product add product_ID int primary key identity(1,1)
suppose this will be help full for you.
There can only be one auto increment field per table. But, you could have a calculated field based on the auto increment field. Or, you could have an int field where you manage the sequence by front end code or by a trigger. And also you could use a sequence in SQL Server.
CREATE SEQUENCE MySequence START WITH 100;
CREATE TABLE MyTable
(
RealIdentity INT IDENTITY(1,1),
RandomCol NVARCHAR(100),
FakeIdentity INT DEFAULT NEXT VALUE FOR MySequence
);
UPDATE - MySQL Way
I just noticed that your question is taged for MySQL. Above answer is for MS SQL. Here's how you'd do the same in MySQL.
How do I create a sequence in MySQL?
MySQL equivalent of Oracle's SEQUENCE.NEXTVAL

Auto Index in My SQL

I am using MySQL for my database. I have a requirement to store a list of users in the system. The user will have both first name and last name.
I cannot have the first name and second name as the primary key. So I need a indexing key. But I do not want to enter the index value every time to add a new row.
I want the system to handle this with auto increment of previous value every time I try to add a new user. Please let me know how to do this.
Also I am supposed to do a search operation on the list of user with the first name. Please let me know the efficient way to do the search as the number of records could be more than a million.
create table users (
id int primary key auto_increment,
name varchar(64),
...
)
See here for more info
Add an INT() id column with auto_increment set. This way, the id column value will be incremented automatically on each INSERT.
To get a unique key without having to specify it, you need an auto_increment field:
create table people (
person_id int primary key auto_increment,
first_name varchar(50),
: : :
);
For efficiently searching first names, you just need an index on the first-name column. A couple of million rows is not a big table, so this should be reasonably efficient.
create index person_index using btree on people (first_name);

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.