2013-07-19 20 views
9

我使用PostgreSQL,並想知道可以有多大的ID得到PostgreSQL的

id INTEGER PRIMARY KEY 

多大可以得到比

id SERIAL PRIMARY KEY 

Java中的int是4個字節(32位)所以它可以達到2,147,483,647。這是在postgresql的情況?如果是這樣,那意味着我不能超過2,147,483,647行?

+0

很好地回答@Goat CO,但是你不能打擾檢查在線手冊的限制類型?我預計未來你會遇到很多問題...... –

回答

19

這裏是PostgreSQL的一個方便的圖表:

Name  Storage Size Description      Range 
smallint 2 bytes   small-range integer    -32768 to +32767 
integer  4 bytes   usual choice for integer   -2147483648 to +2147483647 
bigint  8 bytes   large-range integer    -9223372036854775808 to 9223372036854775807 
serial  4 bytes   autoincrementing integer   1 to 2147483647 
bigserial 8 bytes   large autoincrementing integer 1 to 9223372036854775807 

Source

你的評價是正確的,你用完了唯一的ID,如果你使用的是不足的數據類型。

+1

..但是如果你使用'bigint'(或'bigserial',這是同樣的事情)[你確實真的不會用完](http: //stackoverflow.com/questions/13132939/what-happens-when-i-exhaust-a-bigint-generated-key-how-to-handle-it/13133035#13133035)。 –

3

The data types smallserial, serial and bigserial are not true types, but merely a notational convenience for creating unique identifier columns (similar to the AUTO_INCREMENT property supported by some other databases)

bigserial是8個字節長。如果這還不夠,可以使用128 bits uuid

create table t (
    id uuid primary key 
); 
insert into t (id) 
select uuid_generate_v1mc(); 
select * from t; 
        id     
-------------------------------------- 
916bf7e6-f0c2-11e2-8d14-d372d5ab075f 

uuid_generate_v1mc功能由uuid-ossp module

的UUID功能的主要優勢提供的是它們生成的ID,這是非常有可能在不同的系統中是唯一的。 A serial將在這些系統之間發生衝突。

+0

在這裏,我認爲我處理的萬億記錄表很大,無法想象需要超過九個萬字ID。 –

+1

嘿......人們害怕窮舉一個'bigint'鍵[只是沒有做過數學](http://stackoverflow.com/questions/13132939/what-happens-when-i-exhaust-a-bigint-生成的密鑰 - 如何到柄它/ 13133035#13133035)。 'uuid'鍵對於分佈式系統可以非常方便,但對於關鍵耗盡問題是不必要的。 –

+0

@CraigRinger由於生日悖論bigint可能在鍵被「耗盡」之前很長時間有衝突。 UUID有128位來避免這個問題。 –