Click here to Skip to main content
15,891,704 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,

A newbie question.

Lets say I need to create a database called 'Cars' and I want to 'auto increment' the 'CarId' column.

I would use the following statement for this particular column:
SQL
CarId int IDENTITY(1,1) Primary Key 


Every time a new record is inserted into the database it would add a number to the CarId as 1, 2, 3, 4 and so on.

What if I wanted to allocate a random 8 digit 'CarId' number or an ordered 8-digit 'CarId' number, what would be the best way of going about this?

Please can someone advise.

Thanks

What I have tried:

I'm learning to work with SQL Server 2012 Express
Posted
Updated 8-Aug-18 1:08am
Comments
Skipton Corp 9-Aug-18 3:58am    
Thank you for the solution.

1 solution

Random is a bad idea: they clash far too often. If you want "random ids" then use UNIQUEIDENTIFIER instead, but they are most definitely not 8 digit!

Orders is what you get from IDENTITY, and integers are always potentially 8 digit (just they start with 7 or them having leading zeros.
One way to get a "true" 8 bit sequence is to define your column as
SQL
CarID INT IDENTITY(10000000, 1) PRIMARY KEY
Which means they start from 10,000,000 and go up from there.
 
Share this answer
 
Comments
MadMyche 8-Aug-18 12:01pm    
To add onto this, random numbers being thrown into a primary key or otherwise indexed column has a tendency to fragment the index and reduce performance

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900