Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Share auto-incremented primary key between two tables

Tags:

sql

sql-server

Hi I want to have two tables each have an INT "id" column which will auto-increment but I don't want either "id" columns to ever share the same number. What is this called and what's the best way to do it? Sequence? Iterator? Index? Incrementor?

Motivation: we're migrating from one schema to a another and have a web-page that reads both tables and shows the (int) ID, but I can't have the same ID used for both tables.

I'm using SQL Server 9.0.3068.

Thanks!

like image 316
user24881 Avatar asked Oct 03 '08 15:10

user24881


People also ask

Can two tables share the same primary key?

Every table can have (but does not have to have) a primary key. The column or columns defined as the primary key ensure uniqueness in the table; no two rows can have the same key. The primary key of one table may also help to identify records in other tables, and be part of the second table's primary key.

Can a primary key be auto increment?

Auto-increment allows a unique number to be generated automatically when a new record is inserted into a table. Often this is the primary key field that we would like to be created automatically every time a new record is inserted.

What is it called when two tables share the same primary key?

First when two tables have the same Primary Key and have a foreign key relationship, that means they have a one-to-one relationship.


3 Answers

Just configure the identity increment to be >1 e.g. table one uses IDENTITY (1, 10) [1,11,21...] and table two uses IDENTITY (2, 10) [2,12,22...]. This will also give you some room for expansion if needed later.

like image 105
ballpointpeon Avatar answered Nov 02 '22 23:11

ballpointpeon


I think using a GUID would be the most straightforward way, if I understand you correctly.

SELECT NEWID()
like image 26
Galwegian Avatar answered Nov 03 '22 00:11

Galwegian


Use a column with GUID (Globally Unique Identifier) type. It's 16 byte and will be always unique for each row.

Just be aware that you'll get a significant performance hit comparing to normal integer keys.

like image 26
Ilya Kochetov Avatar answered Nov 02 '22 23:11

Ilya Kochetov