Postgresql – How does Postgres handle integer data of different sizes in the same column

database-internalsintegerpostgresql

If I have a bigint column and in one row store 1 and in another store 999999999999, will these take up different amounts of space on disk?

Will Postgres have an easier time doing queries and calculations with the smaller data?

The motivation for my question is that I have a lot of data in this form: 1000000306429071. I'm wondering if it will be valuable to strip the 1 and leading 0s.

Best Answer

If I have a bigint column and in one row store 1 and in another store 999999999999, will these take up different amounts of space on disk?

Bigint is always 8 bytes regardless of what the decimal representation is

1            | 000000000000000000000000000000000000000000000000000000000000‌​0001
999999999999 | 000000000000000000000000111010001101010010100101000011111111‌​1111

Will Postgres have an easier time doing queries and calculations with the smaller data?

Yes. int4 takes half the amount of space as int8. That means at most you'll save 4 bytes per tuple in the row, and the index will be half the size.

The motivation for my question is that I have a lot of data in this form: 1000000306429071. I'm wondering if it will be valuable to strip the 1 and leading 0s.

That sounds like a wise idea to me. The max value for an int4, is 2147483647, putting them next to each other.

2147483647
306429071

You can see that you're not even close to exhausting that range. You're only 14% there. Do you ever expect to need more than 2147483647? If so, you definitely want to stay with int8.

You can return the value with..

1e15::bigint + 306429071