Store very little Integer in DB( PostgreSQL )
How to store very little Integer (4 bits) integer in my database?
Hi.🙌
In my model, I want to store a very small integer in my DB and I don't want to use SmallIntegerField.
Because Django will store 16 Byte data in DB, which is too much for my need. How can I store 4 bits integers or even less in PostgreSQL?
Thanks for your help.🙏
As Adrian said, the smallest storage for PostgreSQL itself is 2 bytes. There is nothing smaller than that.
If you want to make a constraint, create a maximum check via the save
method in a Django model or add a field validator in the Django field.
2 bytes is the smallest, but there is nothing else
If you really want a database with such constraints, you can install an extension and make your own DB field by following this:
https://dba.stackexchange.com/questions/159090/how-to-store-one-byte-integer-in-postgresql
In Postgres, you can use char(1)
as data type which is stored on 1 Byte if your database is UTF-8 encoded and the values you stores correspond to ascii values less than 128 (see wikipedia) :
CREATE TABLE test (verysmallinteger char(1)) ;
You can then store integer value i from 1 to 32 with :
INSERT INTO test (verysmallinteger ) VALUES chr(i+32)
and you can retrieve the stored values with :
SELECT ascii(verysmallinteger) - 32 FROM test
see dbfiddle