Home » Mysql » Why unsigned integer is not available in PostgreSQL?

Why unsigned integer is not available in PostgreSQL?

Posted by: admin November 1, 2017 Leave a comment

Questions:

I came across this post (What is the difference between tinyint, smallint, mediumint, bigint and int in MySQL?) and realized that PostgreSQL does not support unsigned integer.

Can anyone help to explain why is it so?

Most of the time, I use unsigned integer as auto incremented primary key in MySQL. In such design, how can I overcome this when I port my database from MySQL to PostgreSQL?

Thanks.

Answers:

It is already answered why postgresql lacks unsigned types. However I would suggest to use domains for unsigned types.

http://www.postgresql.org/docs/9.4/static/sql-createdomain.html

 CREATE DOMAIN name [ AS ] data_type
    [ COLLATE collation ]
    [ DEFAULT expression ]
    [ constraint [ ... ] ]
 where constraint is:
 [ CONSTRAINT constraint_name ]
 { NOT NULL | NULL | CHECK (expression) }

Domain is like a type but with an additional constraint.

For an concrete example you could use

CREATE DOMAIN uint2 AS int4
   CHECK(VALUE >= 0 AND VALUE < 65536);

Here is what psql gives when I try to abuse the type.

DS1=# select (346346 :: uint2);

ERROR: value for domain uint2 violates check constraint “uint2_check”

Questions:
Answers:

It’s not in the SQL standard, so the general urge to implement it is lower.

Having too many different integer types makes the type resolution system more fragile, so there is some resistance to adding more types into the mix.

That said, there is no reason why it couldn’t be done. It’s just a lot of work.

Questions:
Answers:

You can use a CHECK constraint, e.g.:

CREATE TABLE products (
    product_no integer,
    name text,
    price numeric CHECK (price > 0)
);

Also PostgreSQL has serial and bigserial types for auto-increment.