patternsqlMajor
What is the right data type to store only -1 0 and 1 in postgres column?
Viewed 0 times
thewhatpostgrescolumnstoretypeanddataonlyright
Problem
I want to store only 3 states in a column (if it was 2, I would use a boolean)
I considered using an
Is there a better way to store only -1 0 and 1 in a PostgresQL column?
I considered using an
ENUM('up', 'down', 'none') but it seems ENUMs take some significant space.Is there a better way to store only -1 0 and 1 in a PostgresQL column?
Solution
If you want to save space, you can use the
you can cast
An enum uses 4 bytes since it is internally stored as a
You should not use
What you are out to save space, you'll have to take alignment into account. The values are always aligned according to the type alignment. For example, a
Now if your table is defined as
there will be 7 padding bytes between the columns, which would render all the space gains from
So place your table columns carefully.
"char" data type. It stores a single byte.you can cast
integer or text to "char":SELECT 'u'::"char", 'd'::"char", 'n'::"char";
char | char | char
------+------+------
u | d | n
(1 row)An enum uses 4 bytes since it is internally stored as a
real.You should not use
"char" with non-ASCII characters!What you are out to save space, you'll have to take alignment into account. The values are always aligned according to the type alignment. For example, a
bigint always has to start at an address that is divisible by 8.Now if your table is defined as
CREATE TABLE (
smallflag "char",
largenum bigint
);there will be 7 padding bytes between the columns, which would render all the space gains from
"char" moot.So place your table columns carefully.
Code Snippets
SELECT 'u'::"char", 'd'::"char", 'n'::"char";
char | char | char
------+------+------
u | d | n
(1 row)CREATE TABLE (
smallflag "char",
largenum bigint
);Context
StackExchange Database Administrators Q#254532, answer score: 27
Revisions (0)
No revisions yet.