Search code examples
postgresqlrange-types

How do I create an custom range type in PostgreSQL for example from 1 to 100?


I have a column that I want to accept values from 1 to 100, is it possible ? I know this is accomplished with functions, but I'm looking for a simple solution as mentioned above.


Solution

  • You can use a check constraint:

    create table foo
    ( 
       some_value int not null check (some_value between 1 and 100)
    );
    

    Alternatively if you need that in multiple tables, a domain might be useful

    create domain one_to_hundred
      as integer not null
      check (value between 1 and 100);
    
    create table foo
    ( 
       some_value one_to_hundred
    );