0

I am using Postgresql. I would like to write a SELECT statement with a column value based on the value in the database.

For example.

|  id  |  indicator  |
|   1  |       0     |
|   2  |       1     |

indicator can be 0 or 1 only where 0 = manual and 1 = auto.

Expected output from a SELECT *

1 manual
2 auto

1 Answer 1

4

You can use a case expression:

select id, case indicator
             when 0 then 'manual'
             when 1 then 'auto'
           end as indicator
from the_table;

If you need that frequently you could create a view for that.

In the long run, it might be better to create a proper lookup table and join to that:

create table indicator
(
  id integer primary key, 
  name text not null
);
insert into indicator (id, name)
values (0, 'manua', 1, 'auto');

alter table the_table 
   add constraint fk_indicator 
   foreign key (indicator) references indicator (id);

Then join to it:

select t.id, i.name as indicator
from the_table t
  join indicator i on i.id = t.indicator;
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, that works (I just have to wait 10 min to mark as the answer)

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.