1

I am new to postgresql. I want to create types in SQL with below values but got stuck to create the same.

I understand its similar like table but I am unable to figure out the solution.

I want to create following types using postgresql

"Completed", "Pending", "Failed", "Created"
2
  • 6
    Hint: CREATE TYPE ... AS ENUM (...) Commented Oct 25, 2018 at 17:02
  • 2
    Use a table with a foreign keys. Enums are vary rarely a good choice Commented Oct 26, 2018 at 6:29

2 Answers 2

2

The correct way to do this, is to use a lookup table and a foreign key:

create table status
(
   id   integer primary key,
   name text not null 
);

insert into status (id, name) 
values
  (1, 'Completed'),
  (2, 'Pending'),
  (3, 'Failed'),
  (4, 'Created');

create table some_table
(
   id integer primary key, 
   status_id integer not null references status
);

That is the most flexible way to handle this in a relational database.

If you know that you will hardly ever change those values, you can use a check constraint:

create table some_table
(
   id integer primary key, 
   status text not null, 
   constraint check_status 
       status in ('Completed', 'Pending', 'Failed', 'Created')
);

This has the disadvantage that you are storing the same values over and over again, so the size of the table will be bigger compared to the foreign key solution.

The third option is to use an enum type

create type status_type AS ENUM (''Completed', 'Pending', 'Failed', 'Created');

Then use that type in the table:

create table some_table
(
   id integer primary key, 
   status status_type not null
);

This has a similar storage requirement as the foreign key solution but displays the status as "clear text".

Sign up to request clarification or add additional context in comments.

Comments

0
   CREATE TYPE color AS ENUM ('red', 'green', 'blue');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.