I'm writing a query to create a table in Access with an AutoNumber column. I want to do this only using SQL (I
won't go into why). However, since Autonumber is not a datatype, but a property, how can I set this using only SQL? Do you know the SQL syntax for creating an autonumber column in Access?
Yes, you can create a Microsoft Access autoincrement column using Data Definition Language (DDL). As described in the document Intermediate Microsoft Jet SQL for Access 2000, you declare it as a COUNTER datatype:
The COUNTER data type is used to store long integer values that automatically increment whenever a new record is inserted into a table. With the COUNTER data type, you can optionally set a seed value and an increment value... You can have only one COUNTER field in a table, and the synonyms are COUNTER, AUTOINCREMENT, and IDENTITY.
The above document also mentions that @@IDENTITY can be used to retrieve the value of the last counter number assigned. To the best of my knowledge, this feature was introduced in Access 2000. Always use this instead of techniques such as querying the table for MAX(id).
According to KB Article Q116145 ACC: Create and Drop Tables and Relationships Using SQL DDL, COUNTER in DDL is valid as far back as Access Version 2.0.
For More Information
- Dozens more answers to tough SQL questions from Rudy Limeback.
- The Best SQL Web Links: tips, tutorials, scripts, and more.
- Have an SQL tip to offer your fellow DBAs and developers? The best tips submitted will receive a cool prize. Submit your tip today!
- Ask your technical SQL questions -- or help out your peers by answering them -- in our live discussion forums.
- Ask the Experts yourself: Our SQL, database design, Oracle, SQL Server, DB2, metadata, object-oriented and data warehousing gurus are waiting to answer your toughest questions.
Dig deeper on Oracle and SQL
Have a question for an expert?
Please add a title for your question
Get answers from a TechTarget expert on whatever's puzzling you.