Unique random integer as primary key ID instead of auto increment [duplicate] - sql

This question already has answers here:
How to to create unique random integer ID for primary key for table?
(8 answers)
Closed 4 years ago.
Right now I have one table of members with table primary key 'id' as auto incremented.
I want that instead of auto increment, it will generate a random integer of 5-6 digits and put that as 'id'. As every 'id' is primary key so generated int will be unique. Any ideas to implement this on sql server will help.

You can use CHECKSUM with NEWID() and use it as a DEFAULT like this.
SELECT ABS(CHECKSUM(NEWID())) % 100000
% 100000 is optional if you want to restrict the number to be max 5 digit.
Note: Having random generated clustered key will cause page splits during inserts.

To avoid guessing the total number of users, just add a random value as initial value when creating the database.
CREATE TABLE users
(
ID int identity (7854, 7),
)
When also specifying an increment value > 1, you loose values of course. Check the value range with the expected number of records.
Another (much better) option would be to hide the primary keys from your users, and if they need to see some identification, they should see a value that is separate from the primary key. Add another value to the table, called "visible ID" or something.

Try using RAND function as below to generate 6 digit random number
select ceiling(RAND()*1000000)

CREATE TABLE NEWID_TEST
(
ID UNIQUEIDENTIFIER DEFAULT NEWID() PRIMARY KEY,
TESTCOLUMN CHAR(2000) DEFAULT REPLICATE('X',2000)
)
GO
-- or use
CREATE TABLE NEWSEQUENTIALID_TEST
(
ID UNIQUEIDENTIFIER DEFAULT NEWSEQUENTIALID() PRIMARY KEY,
TESTCOLUMN CHAR(2000) DEFAULT REPLICATE('X',2000)
)
GO

Related

Sqlite - composite PK with two auto-incrementing values [duplicate]

I have a composite primary key {shop_id, product_id} for SQLite
Now, I want an auto-increment value for product_id which resets to 1 if shop id is changed. Basically, I want auto-generated composite key
e.g.
Shop ID Product Id
1 1
1 2
1 3
2 1
2 2
3 1
Can I achieve this with auto-increment? How?
Normal Sqlite tables are B*-trees that use a 64-bit integer as their key. This is called the rowid. When inserting a row, if a value is not explicitly given for this, one is generated. An INTEGER PRIMARY KEY column acts as an alias for this rowid. The AUTOINCREMENT keyword, which can only be used on said INTEGER PRIMARY KEY column, contrary to the name, merely alters how said rowid is calculated - if you leave out a value, one will be created whether that keyword is present or not, because it's really the rowid and must have a number. Details here. (rowid values are generally generated in increasing, but not necessarily sequential, order, and shouldn't be treated like a row number or anything like that, btw).
Any primary key other than a single INTEGER column is treated as a unique index, while the rowid remains the true primary key (Unless it's a WITHOUT ROWID table), and is not autogenerated. So, no, you can't (easily) do what you want.
I would probably work out a database design where you have a table of shops, a table of products, each with their own ids, and a junction table that establishes a many-to-many relation between the two. This keeps the product id the same between stores, which is probably going to be less confusing to people - I wouldn't expect the same item to have a different SKU in two different stores of the same chain, for instance.
Something like:
CREATE TABLE stores(store_id INTEGER PRIMARY KEY
, address TEXT
-- etc
);
CREATE TABLE product(prod_id INTEGER PRIMARY KEY
, name TEXT
-- etc
);
CREATE TABLE inventory(store_id INTEGER REFERENCES stores(store_id)
, prod_id INTEGER REFERENCES product(prod_id)
, PRIMARY KEY(store_id, prod_id)) WITHOUT ROWID;

Function in SQL that will give me a unique int?

I am trying to enter a row into one of my databases, but I want to make sure the primary key I give it is unique. My primary key is an int. I have tried using newid(), but that does not give me an int back. If there is a way I can get newid() to return just an int, or if another function that would give me an unique int I would use it.
You could alter the definition of your column to int IDENTITY(1,1) PRIMARY KEY, then don't specify a value when inserting a row, and the ID will auto-increment.
See https://www.w3schools.com/sql/sql_autoincrement.asp for more info.
Be careful with a random primary key, especially if it's the clustered index too. It's likely to cause allot of filesystem IO.
Use an auto incrementing identity instead.
One object that gives unique ints are the sequences.
You first need to create a sequence :
CREATE SEQUENCE MyNewID START WITH 1 INCREMENT BY 1;
And then you can retrieve your new ID calling NEXT VALUE every time :
SET #MyNewID = NEXT VALUE FOR MyNewID;

Which is smaller storage: an identity primary key or a sequence primary key?

Which is smaller storage: an identity primary key or a sequence primary key? An example of what I mean by sequence is below.
CREATE SEQUENCE TestSeq
AS INTEGER
START WITH 1
INCREMENT BY 1;
CREATE TABLE Tab1
(tab1_ID INTEGER DEFAULT NEXT VALUE FOR TestSeq PRIMARY KEY,
other_stuff VARCHAR(15) NOT NULL);
Bonus: Any recommended links for Sequence would also welcomed. I am trying to figure out there place vs Identity.
As far as data size goes they are effectively identical (assuming that the type is the same).
The difference is that a sequence is separate from the table, and the numbers in it can be used to uniquely identify rows across multiple tables (occasionally useful) or used to generate unique numbers in a procedure without having to insert a row into a table at all.

SQL Identify Auto Increment from a certain number

I am trying to auto increment my primary key, by 0.1 each time. Starting from 0.1. Is this possible?
CREATE TABLE NewTable
(
ID BigInt IDENTITY NOT NULL,
CONSTRAINT PK_ID PRIMARY KEY (ID),
)
No. BigInt is a 8 byte integer value.
Note: Assuming as Microsoft SQL Server.
No, even if you changed the data type of the field, the identity increment 'must be a non-zero integral number containing 18 digits or less'
(Presuming this is sql server)
In SQL Server, the Identity column cannot contain decimal values in its seed or increment.
Why would you need to do this -- for presentation purposes? If so, don't. If needed, one option is to create a trigger. You could also consider using a Computed column instead -- make it 1/10 the value of the Id (your Identity field seeded and incremented at 1 -- Identity(1,1)).
Again, not sure why you'd need to do this though.
Some solution would be a view:
CREATE VIEW v_NewTable AS
SELECT ID/10
FROM NewTable

SQLite: autoincrement primary key questions

I have the following SQLite query:
CREATE TABLE Logs ( Id integer IDENTITY (1, 1) not null CONSTRAINT PKLogId PRIMARY KEY, ...
IDENTITY (1, 1) -> What does this mean?
PKLogId what is this? This doesn't seem to be defined anywhere
I want Id to be integer primary key with autoincrement. I would like to be able to insert into this Logs table omitting Id column in my query. I want Id to be automatically added and incremented. Is this possible? How can I do this?
At the moment when I try to insert without Id I get:
Error while executing query: Logs.Id may not be NULL
I'm not sure whether you're actually using SQLite according to the syntax of your example.
If you are, you may be interested in SQLite FAQ #1: How do I create an AUTOINCREMENT field?:
Short answer: A column declared INTEGER PRIMARY KEY will
autoincrement.
Change it to:
CREATE TABLE Logs ( Id integer PRIMARY KEY,....
If you are, you may be interested in SQLite FAQ #1: How do I create an AUTOINCREMENT field?:
Short answer: A column declared INTEGER PRIMARY KEY will auto increment.
This in fact is not entirely accurate. An integer primary key will indeed increment, however if the table drops all rows, it starts from the beginning again, It is important if you want to have all associated records tied correctly to use the autoincrement description after the primary key declaration on the integer field.